Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict file types being uploaded to Spring MVC3 Controller

I am using Spring MVC3 to handle file upload for my web application. For now, I can restrict the file size being uploaded using the following configuration defined in my xml context file:

<beans:bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <beans:property name="maxUploadSize" value="200000"/> 
</beans:bean>

I have scoured the web for how to restrict the file type but to no avail. Most of the articles I found only teach how to restrict the file size not the file type. Thank in advance for your help.

like image 937
woraphol.j Avatar asked Jan 04 '13 10:01

woraphol.j


People also ask

How do I restrict a file type in FileUpload control?

By default the FileUpload control doesn't have a property to restrict file types when the select file window is opened. However, you can check the file uploaded extension before continuing the process. Its simple. Get the extension of the file selected via FileUpload control using the below code.

Which of the following is the dependency that is needed to support uploading of 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

Try performing the check/routing in your controller's request handler method:

@RequestMapping("/save")
public String saveSkill(@RequestParam(value = "file", required = false) MultipartFile file) {   
        if(!file.getContentType().equalsIgnoreCase("text/html")){
            return "normalProcessing";
        }else{
            return "redirect: /some/page";
        }
}
like image 137
Kevin Bowersox Avatar answered Nov 12 '22 06:11

Kevin Bowersox


You restrict file uploading by file types, you can extend org.springframework.web.multipart.commons.CommonsMultipartResolver class. And add method to check file content-type or file type using MultipartFile.

Provide file types , those you want to restrict in configuration like -

 <beans:bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <beans:property name="maxUploadSize" value="200000"/> 
    <beans:property name="restrictFileTypes" value="html,pdf,..."/> 
</beans:bean>
like image 32
Avinash T. Avatar answered Nov 12 '22 05:11

Avinash T.