1、CommonsMultipartResolver介绍
该类是spring在apache common fileupload组件的基础上,进行了一层封装,使用更方便。
备注,CommonsMultipartResolver类的初始化有两种方式:a、spring上下文 b、“the constructor that takes a ServletContext (for standalone usage)”。
这两种方式不要混用
2、在spring上下文中,配置CommonsMultipartResolver
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760000"></property><!-- 最大上传文件大小 -->
</bean>
3、上传REST服务/Servlet代码编写
@Controller
@RequestMapping(value = "/rest")
public class NewFileUploadTestController {
private static final Log logger = LogFactory.getLog(NewFileUploadTestController.class);
@RequestMapping(value = "/fileUploadFunc", method = RequestMethod.POST)
@ResponseBody
public String fileUpload(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");
System.out.println(multipartRequest.getParameter("note"));
// 上传后记录的文件...
File imageFile = new File("d:/fileName");
try {
file.transferTo(imageFile);
} catch (IllegalStateException e) {
logger.error(e);
} catch (IOException e) {
logger.error(e);
}
return "ok";
}
}
4、前端代码片段
<form method="post" enctype="multipart/form-data" action="rest/rest/fileUploadFunc.restctrl">
File to upload: <input type="file" name="file""><br/>
Notes about the file: <input type="text" name="note"><br/>
<br/>
<input type="submit" value="Press"> to upload the file!
</form>