Spring MVC 上传文件
本篇帖子讲解使用异步方式上传文件, 使用 jquery.form.js 来实现;
一、配置spring的配置文件
<!-- 上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <property name="maxUploadSize" value="10485760000"></property> <property name="maxInMemorySize" value="40960"></property> </bean>
二、前台的文件
1、jsp文件
<form id="jvForm" action="o_save.shtml" method="post"> <table cellspacing="1" cellpadding="2" width="100%" border="0" class="pn-ftable"> <tbody> <tr> <td width="20%" class="pn-flabel pn-flabel-h"> <span class="pn-frequired">*</span>上传商品图片(90x150尺寸): </td> <td width="80%" class="pn-fcontent"> 注:该尺寸图片必须为90x150。 </td> </tr> <tr> <td width="20%" class="pn-flabel pn-flabel-h"></td> <td width="80%" class="pn-fcontent"> <img width="100" height="100" id="imgSize1ImgSrc"/> <input type="file" name="pic" onchange="uploadPic()"/> </td> </tr> </tbody> <tbody> <tr> <td class="pn-fbutton" colspan="2"> <input type="submit" class="submit" value="提交"/> <input type="reset" class="reset" value="重置"/> </td> </tr> </tbody> </table> </form>
2、js文件
function uploadPic() { //异步上传 jquery.form.js插件 //使用js模拟表单异步上传 var options = { url : "/upload/uploadPic.do", type : "POST", dataType : "json", success : function(data){ //data } }; $("#jvForm").ajaxSubmit(options); }
三、java代码
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class UploadController { //上传单张图片 @RequestMapping(value = "/upload/uploadPic.do") public void toEdit(@RequestParam(required = false) MultipartFile pic) { System.out.println(pic.getOriginalFilename()); } }
参考: https://www.cnblogs.com/lichenwei/p/4160342.html