我成功地使用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中,文件夹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;
}
3条答案
按热度按时间ebdffaop1#
请参考以下示例:
gg58donl2#
请尝试此方法加载资源。以查看是否有效
资源文件=文件存储服务.loadFileAsResource(文件名);
ryoqjall3#
请尝试以下代码
我不确定它是否适用于您的系统,但对我来说,我仍然使用这种方法来正常下载文件。