How to restrict file types being uploaded to Spring MVC3 Controller
Solution 1
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";
}
}
Solution 2
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>
Solution 3
You can create a user defined method to do this check:
String fileExtensions = ".exe,.dmg,.mp3,.jar";
String fileName = multipartFile.getOriginalFilename();
int lastIndex = fileName.lastIndexOf('.');
String substring = fileName.substring(lastIndex, fileName.length());
And check the condition:
if (!fileExtensions.contains(substring.toLowerCase()))
//reject logic
else
//accept logic
Solution 4
You can also check the Mime Type and according to that you can restrict the user to upload the files JMimeMagic Library will be used here.
MagicMatch match = Magic.getMagicMatch(file.getBytes());
System.out.println(match.getMimeType());
Related videos on Youtube
Comments
-
woraphol.j over 1 year
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.
-
TheRealChx101 over 2 yearsDoesn't that come from the client? Could easily be spoofed.