📅  最后修改于: 2020-11-11 06:27:59             🧑  作者: Mango
以下示例显示了如何使用Spring Web MVC框架在表单中使用文件上载控件。首先,让我们拥有一个可用的Eclipse IDE,并遵循以下步骤来使用Spring Web Framework开发基于动态表单的Web应用程序。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. |
2 | Create Java classes FileModel, FileUploadController under the com.tutorialspoint package. |
3 | Create view files fileUpload.jsp, success.jsp under the jsp sub-folder. |
4 | Create a folder temp under the WebContent sub-folder. |
5 | Download Apache Commons FileUpload library commons-fileupload.jar and Apache Commons IO library commons-io.jar. Put them in your CLASSPATH. |
6 | The final step is to create the content of the source and configuration files and export the application as explained below. |
package com.tutorialspoint;
import org.springframework.web.multipart.MultipartFile;
public class FileModel {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
package com.tutorialspoint;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class FileUploadController {
@Autowired
ServletContext context;
@RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
public ModelAndView fileUploadPage() {
FileModel file = new FileModel();
ModelAndView modelAndView = new ModelAndView("fileUpload", "command", file);
return modelAndView;
}
@RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
if (result.hasErrors()) {
System.out.println("validation errors");
return "fileUploadPage";
} else {
System.out.println("Fetching file");
MultipartFile multipartFile = file.getFile();
String uploadPath = context.getRealPath("") + File.separator + "temp" + File.separator;
//Now do something with file...
FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename()));
String fileName = multipartFile.getOriginalFilename();
model.addAttribute("fileName", fileName);
return "success";
}
}
}
在这里,对于第一个服务方法fileUploadPage() ,我们在ModelAndView对象中传递了一个名称为“ command”的空白FileModel对象,因为如果您使用的是