基于Spring的CommonsMultipartResolver类进行文件上传

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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值