Nic*_*ote 3 java spring spring-mvc postman spring-rest
我正在尝试在我的 Restful Spring Boot 应用程序中实现 pdf 文件上传。
我有以下方法;
@RequestMapping(value = FILE_URL, method = RequestMethod.POST)
public ResponseDTO submitPDF(
@ModelAttribute("file") FileDTO file) {
MediaType mediaType = MediaType.parseMediaType(file.getFile().getContentType());
System.out.println(file.getFile().getContentType());
System.out.println(mediaType);
System.out.println(mediaType.getType());
if(!"application/pdf".equals(mediaType.getType())) {
throw new IllegalArgumentException("Incorrect file type, PDF required.");
}
... more code here ...
}
Run Code Online (Sandbox Code Playgroud)
FileDTO 只是 MultipartFile 的包装器。
然后我使用 Postman 用form-databody 发布请求'file'=<filename.pdf>
上面 printlns 中的内容类型始终是八位字节流。无论我发送什么类型的文件(png、pdf 等),它始终是八位字节流。如果我application/pdf在 Postman 中专门设置为 Content-Type 标头,则 FileDTO 中的 MultipartFile 最终为空。
问题是,我的 Spring Controller 方法有问题,还是 Postman 没有正确构建请求?
如果 Postman 无法正确获取 Content-Type,我是否可以期望实际的客户端应用程序将内容类型正确设置为 pdf?
小智 5
您是否尝试过Apache Tika库来检测上传文件的 MIME 类型?
Kotlin 中的代码示例
private fun getMimeType(file: File) = Tika().detect(file)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9033 次 |
| 最近记录: |