Spring MVC boot file - how is the content type determined?

I am using Spring 3 to upload a file. I would like to know how best to verify that the file is of a specific type, in particular the csv file. I am sure that checking the extension is useless, and I'm currently checking the type of contents of the uploaded file. I just guarantee that it is of type "text / csv". And just for clarification, this is a file downloaded by the client, that is, I do not control its origin.

I am curious how Spring / browser determines the type of content? Is this the best / safe way to determine which file has been downloaded? Can I ever be 100% sure?

UPDATE: Again, I am not interested in how to determine the type of file content, but how the type of content is determined. How does Spring / browser know that the content type is "text / csv" based on the downloaded file?

+5
source share
5 answers

you can use

org.springframework.web.multipart.commons.CommonsMultipartFile an object.

has a method getContentType();.

Have a look at the following example http://www.ioncannon.net/programming/975/spring-3-file-upload-example/

you can simply add a simple test to the CommonsMultipartFile object and redirect to the error page if this is the wrong content type.

+1
source

, . , CSV .

+1

, - fileName.split( "\." ) [filename.length() - 1] string

0

, java- Csvreader. csvreader .

0

, getContentType(String) , , , , .

For binary files, you can check the magic number or use a library like mime-util or jMimeMagic . There is also Files.probeContentType(String)Java 7, but it only works with files on disk, and error is reported on some operating systems.

0
source

All Articles