我使用 multipart 成功上傳了一個檔案并將物體類 ID 附加到它。發送一個 get 請求會回傳一個空值。
這是我的帖子端點:
@PostMapping("/{id}/upload_multiple")
public ResponseEntity<ResponseMessage> createDocument(@PathVariable Long id,
@RequestParam("applicationLetter") MultipartFile appLetter,
@RequestParam("certificateOfInc") MultipartFile cInc, @RequestParam("paymentReceipt") MultipartFile payment,
@RequestParam("taxClearance") MultipartFile tax, @RequestParam("staffsResume") MultipartFile staffs,
@RequestParam("letterOfCredibility") MultipartFile credibility,
@RequestParam("workCertificate") MultipartFile workCert,
@RequestParam("consentAffidavit") MultipartFile affidavit,
@RequestParam("collaborationCert") MultipartFile colabo, @RequestParam("directorsId") MultipartFile idcard,
@RequestParam("membership") MultipartFile member) throws IOException {
documentService.create(id, appLetter, cInc, payment, tax, staffs, credibility, workCert, affidavit, colabo,
idcard, member);
String message = "Upload successful";
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
}
上傳的檔案保存在另一個檔案夾 10001 中,這是檔案物體的 ID。我現在的挑戰是從 10001 檔案夾中獲取這些檔案。

這是我嘗試過的,但為所有檔案回傳空值:
@GetMapping( "/files/{filename:. }/{id}")
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
Resource file = documentService.load(filename);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/octet-stream"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" file.getFilename() "\"")
.body(file);
}
我的服務等級:
private final Path root = Paths.get("documents");
@Override
public Resource load(String filename) {
try {
Path file = root.resolve(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new RuntimeException("Could not read the file!");
}
} catch (MalformedURLException e) {
throw new RuntimeException("Error: " e.getMessage());
}
}
我的物體類:
@Entity
@Getter
@Setter
public class Documents {
@Id
@Column(nullable = false, updatable = false)
@SequenceGenerator(
name = "primary_sequence",
sequenceName = "primary_sequence",
allocationSize = 1,
initialValue = 10000
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "primary_sequence"
)
private Long id;
@Column(nullable = false)
private String applicationLetter;
@Column(nullable = false)
private String certOfIncorporation;
@Column(nullable = false)
private String paymentReceipt;
@Column(nullable = false)
private String taxClearance;
@Column(nullable = false)
private String staffsResume;
}
uj5u.com熱心網友回復:
參考這個例子:
@GetMapping("/files")
public ResponseEntity<List<ResponseFile>> getListFiles() {
List<ResponseFile> files = storageService.getAllFiles().map(dbFile -> {
String fileDownloadUri = ServletUriComponentsBuilder
.fromCurrentContextPath()
.path("/files/")
.path(dbFile.getId())
.toUriString();
return new ResponseFile(
dbFile.getName(),
fileDownloadUri,
dbFile.getType(),
dbFile.getData().length);
}).collect(Collectors.toList());
return ResponseEntity.status(HttpStatus.OK).body(files);
}
@GetMapping("/files/{id}")
public ResponseEntity<byte[]> getFile(@PathVariable String id) {
FileDB fileDB = storageService.getFile(id);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" fileDB.getName() "\"")
.body(fileDB.getData());
}
uj5u.com熱心網友回復:
試試這個方法來加載資源。看看它是否有效
資源檔案 = fileStorageService.loadFileAsResource(fileName);
uj5u.com熱心網友回復:
試試這個代碼
@GetMapping( "/files/{filename:. }/{id}")
public void getFile(@PathVariable String filename, HttpServletRequest request, final HttpServletResponse response) {
BufferedInputStream bufferedInputStream = null;
try {
File file = ...;
response.setHeader("Cache-Control", "must-revalidate");
response.setHeader("Pragma", "public");
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-disposition", "attachment; ");
bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
FileCopyUtils.copy(bufferedInputStream, response.getOutputStream());
} catch (Exception e) {
logger.error(e.getMesssage(), e);
} finally {
try {
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (Exception ex) {
logger.error(ex);
}
try {
if (bufferedInputStream != null)
bufferedInputStream.close();
} catch (Exception ex) {
logger.error(ex);
}
}
}
我不確定它是否適用于您的系統,但對我來說,我仍然使用這種方法正常下載檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/514385.html
標籤:爪哇春天弹簧靴
上一篇:使用Kafka模板發送多個DTO
