Spring文件上传内容类型验证,总是八位字节流?

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)

  • 你在跟踪我吗?你在我窗外吗?2 年多没看过这个问题了,就在昨天,我回到了这部分代码并决定扩展文件类型支持,经过多次谷歌搜索,最终找到了 Tika,它对我的​​帮助无穷无尽!但是几个小时后,我收到一封 SO 电子邮件,通知我这个旧问题已更新,您提出了同样的建议?......你是......你是谷歌吗? (3认同)