I am trying to upload a file using Spring MVC. Here is the form in the .jsp page
<form:form method="post" commandName="file" enctype="multipart/form-data">
Upload your file please:
<input type="file" name="file" />
<input type="submit" value="upload" />
<form:errors path="file" cssStyle="color: #ff0000;" />
</form:form>
In my controller I have the GET and POST methods:
@RequestMapping(method = RequestMethod.GET)
public String getForm(Model model) {
File fileModel = new File();
model.addAttribute("file", fileModel);
return "file";
}
@RequestMapping(method = RequestMethod.POST)
public String fileUploaded(Model model, @Validated File file, BindingResult result) {
String returnVal = "successFile";
logger.info("I am here!!!");
if (result.hasErrors()) {
returnVal = "file";
}else{
MultipartFile multipartFile = file.getFile();
}
return returnVal;
}
The validation is just to check if the file size is zero:
public void validate(Object target, Errors errors) {
File imageFile = (File)target;
logger.info("entered validator");
if(imageFile.getFile().getSize()==0){
errors.rejectValue("file", "valid.file");
}
}
The method GET works fine and returns the file view, however the POST method in the controller does not get called. Nothing happens when the upload button is clicked.
I hope this will help you:
controller code
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadInputFiles(@RequestParam("file1") MultipartFile file,
@RequestParam("fileName") String fileName,
@RequestParam("fileType") String fileType){
System.out.println("Upload File Controller has been called");
}
Form submission:
<form method="POST" action="uploadFile" enctype="multipart/form-data">
File to upload: <input type="file" name="file"><br />
Name: <input type="text" name="name"><br /> <br />
<input type="submit" value="Upload"> Press here to upload the file!
</form>
I think your configuration should be like below in mvc-servlet.xml file.
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="500000" />
</bean>
and change your post api like below.
@RequestMapping(method = RequestMethod.POST,value = "/uploadFile")
public String fileUploaded(Model model, @RequestParam("file") MultipartFile file, BindingResult result) {
String result = "not uploaded";
if(!file.isEmpty()){
MultipartFile multipartFile = file.getFile();
//code for storing the file in server(in db or system)
}
else{
result = "can not be empty;"
}
return result;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.