开发者

Spring MVC Upload File - How is Content Type determine?

I'm using Spring 3 ability to upload a file. I would like to know the best way to validate that a file is of a certain type, specifically a csv file. I'm rather sure that checking the extension is usel开发者_JAVA百科ess and currently I am checking the content type of the file that is uploaded. I just ensure that it is of type "text/csv". And just to clarify this is a file uploaded by the client meaning I have no control of its origins.

I'm curious how Spring/the browser determines what the content type is? Is this the best/safest way to determine what kind of file has been uploaded? Can I ever be 100% certain?

UPDATE: Again I'm not wondering how to determine what the content type is of a file but how the content type gets determined. How does spring/the browser know that the content type is a "text/csv" based on the file uploaded?


You can use

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

it hasgetContentType(); method.

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

you can just add the simple test on CommonsMultipartFile object and redirect to error page if it the content type is incorrect.


So you can also count the number of commas in the file per line.There should normally be the same amount of commas on each line of the file for it to be a valid CSV file.


Why you don't just take the file name in you validator and split it, the file type is fileName.split("\.")[filename.length()-1] string


Ok, in this case i suggest you to use the Csvreader java library. You just have to check your csvreader object and that's all.


As far as I'm aware the getContentType(String) method gets its value from whatever the user agent tells it - so you're right to be wary as this can easily be spoofed.

For binary files you could check the magic number or use a library, such as mime-util or jMimeMagic. There's also Files.probeContentType(String) since Java 7 but it only works with files on disk and bugs have been reported on some OSes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜