SpringMVC (15)_File upload

       Foreword: This article mainly introduces how SpringMVC handles file uploads . The usage is super simple and the development efficiency is high.

 

       Spring MVC provides direct support for file uploading via a plug-and-play MultipartResolver. Spring uses Jakarta Commons FileUpload technology to implement a MultipartResolver implementation class: CommonsMultipartResovler.

       The Spring MVC context is not equipped with MultipartResovler by default, so it cannot handle file upload work by default. If you want to use Spring's file upload function, you need to configure MultipartResolver in the context now.

 

1. Add related jar package


  

2. Configure the SpringMVC configuration file

<!-- Configure MultipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="UTF-8"></property>
    <property name="maxUploadSize" value="1024000"></property>  
</bean>

      Note: defaultEncoding: must be consistent with the pageEncoding attribute of the user's JSP in order to correctly parse the content of the form;

 

3. Front desk code

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test file upload</title>
</head>
<body>

	<form action="testFileUpload.action" method="POST" enctype="multipart/form-data">
		File: <input type="file" name="file"/>
		Desc: <input type="text" name="desc"/>
		<input type="submit" value="Submit"/>
	</form>
	
</body>
</html>

      Note: The encoding method is UTF-8, which is consistent with the SpringMVC configuration file; 

 

4. Background code 

@RequestMapping("/testFileUpload.action")
public String testFileUpload(@RequestParam("desc") String desc,
                             @RequestParam("file") MultipartFile file) throws IOException{

    String tomcatPath = System.getProperty("catalina.home");
    File   destFile   = new File(tomcatPath + File.separator + "temp" + File.separator + file.getOriginalFilename());
    file.transferTo(destFile);
    
    System.out.println("desc: " + desc);
    System.out.println("OriginalFilename: " + file.getOriginalFilename());
    return "success";
}

 

 

Code download source: http://super-wangj.iteye.com/blog/2388430

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326334998&siteId=291194637