Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 useless 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?

like image 926
sauce Avatar asked Aug 24 '11 17:08

sauce


People also ask

How would you handle the situation where a user uploads a very large file through a form in your Spring MVC application?

A new attribute "maxSwallowSize" is the key to deal this situation. It should happen when you upload a file which is larger than 2M. Because the 2M is the default value of this new attribute .

Which class provides access to details about a file that has been uploaded from a form in a Spring MVC application?

Spring File Upload Controller Class.

Which dependency is needed to support uploading a file in MVC?

The dependency needed for MVC is the spring-webmvc package. The javax. validation and the hibernate-validator packages will be also used here for validation. The commons-io and commons-fileupload packages are used for uploading the file.


2 Answers

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.

like image 79
danny.lesnik Avatar answered Oct 14 '22 05:10

danny.lesnik


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.

like image 23
Aina Avatar answered Oct 14 '22 07:10

Aina