I'm trying to implement pdf file uploading in my Restful Spring Boot application.
I have the following method;
@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 ...
}
FileDTO is just a wrapper around MultipartFile.
I'm then using Postman to POST the request with form-data
body 'file'=<filename.pdf>
The content type in the printlns above is ALWAYS octet-stream. No matter what type of file I send in (png, pdf, etc) its always octet stream. If I specifically set application/pdf
as Content-Type header in Postman the MultipartFile within FileDTO ends up as null.
Question is, is there something wrong with my Spring Controller method, or is the request just not being built correctly by Postman?
If Postman can't get the Content-Type right, can I expect actual client apps to properly set content type to pdf?
Best Answer
Have you tried Apache Tika library for detecting mime types of uploaded file?
Code Example in Kotlin