Spring MVC - File upload
1. File upload
1.1 File upload must
The enctype value of the form form must be: multipart/form-data (default: application/x-www-form-urlencoded)
B. The method attribute must be post
c. Provide a file selection field.
1.2 principle analysis of file uploading
When the enctype value of the form form is not the default value, request.getParameter () will fail
When enctype="aaplication/x-www-form-urlencoded", the body of the form is:
key=value&key=value&key=value
When enctype="multipart/form-data", the content of the request body becomes:
Each part is a description body of MIME type
---------------------------------- 7de1a433602ac demarcator
Content-Disposition: form-data; name= "userName" protocol header
...
1.3 Dependence on jar packages
2. Traditional way to upload files
Traditional file upload means that the files we upload and the applications we access exist on the same server.
2.1 pom.xml file dependency
<!--Two dependencies on file upload jar package--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
2.2 jsp page
<form action="/user/fileupload01" method="post" enctype="multipart/form-data"> //Select files:<input type="file" name="upload"><br> <input type="submit" value="upload"> </form>
2.3 Writing Controller
@Controller @RequestMapping("/user") public class FileUploadController { /** * Upload files in the original way * @return */ @RequestMapping("/fileupload01") public String testFileUpload(HttpServletRequest request) throws Exception { //File upload using fileupload component //Upload location String realPath = request.getSession().getServletContext().getRealPath("/uploads"); System.out.println(realPath); //Determine whether the path exists File file = new File(realPath); if (!file.exists()){ //Create this folder file.mkdirs(); } //Parse the request object to get the uploaded file item DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload= new ServletFileUpload(factory); //Parsing request List<FileItem> items = upload.parseRequest(request); for (FileItem item: items) { //To determine whether the current item is an uploaded file item if (item.isFormField()){ //Common form items }else { String uuid = UUID.randomUUID().toString().replace("-", ""); //File Upload Item String fileName = uuid + "_" +item.getName(); //Finish uploading item.write(new File(file, fileName)); //Delete temporary files item.delete(); } } System.out.println("Successful file upload"); return "success"; } }
2.4 Profile Parser
<! - File upload id must be = "multipartResolver" --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <! - Upload file size, set here is 10M - >. <property name="maxUploadSize" value="10485760"></property> </bean>
3. Upload files using Spring MVC
3.1 Modify the controller to
/** * Upload files using Spring MVC * MultipartFile upload: The name should be the same as the name value of input * @return */ @RequestMapping("/fileupload02") public String testFileUpload2(HttpServletRequest request, /*@RequestParam(name = "upload") */MultipartFile upload) throws Exception { //File upload using fileupload component //Upload location String realPath = request.getSession().getServletContext().getRealPath("/uploads"); System.out.println(realPath); //Determine whether the path exists File file = new File(realPath); if (!file.exists()){ //Create this folder file.mkdirs(); } String uuid = UUID.randomUUID().toString().replace("-", ""); //File Upload Item String fileName = uuid + "_" + upload.getOriginalFilename(); //Finish uploading upload.transferTo(new File(realPath, fileName)); System.out.println("SpringMVC Successful file upload"); return "success"; }
4. Spring MVC file upload across servers
Purpose of 4.1 sub-server
The purpose of sub-servers is to make the servers perform their duties, so as to improve the efficiency of project operation.
4.2 Prepare two tomcat servers and create a web project for storing images
4.3 In addition to relying on two jar s for file upload, a POM file needs jersey
com.sun.jersey
jersey-core
1.18.1
com.sun.jersey
jersey-client
1.18.1
4.4 Change the controller to
/** * Upload files across servers * MultipartFile upload: The name should be the same as the name value of input * @return */ @RequestMapping("/fileupload03") public String testFileUpload3(HttpServletRequest request, MultipartFile upload) throws Exception { System.out.println("Cross-server file upload"); //File upload using fileupload component //Define the upload server path String path = "http://localhost:9090/uploads/"; //Determine whether the path exists File file = new File(path); if (!file.exists()){ //Create this folder file.mkdirs(); } String uuid = UUID.randomUUID().toString().replace("-", ""); //File Upload Item String fileName = uuid + "_" + upload.getOriginalFilename(); //Creating Client Objects Client client = Client.create(); //Connect to the image server WebResource webResource = client.resource(path + fileName); //Finish uploading webResource.put(upload.getBytes()); System.out.println("SpringMVC Successful file upload"); return "success"; }
Source code: github