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.
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.
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.
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";
}
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With