springmvc下使用formdata异步ajax上传图片

时间:2022-08-29 09:47:02

最近学习springmvc框架,其中一项需求是产品修改页异步上传修改产品图片,使用的是FormData+Jquery,亲测有效,除了ajax返回结果乱码没处理springmvc下使用formdata异步ajax上传图片,下面贴代码

SpringMVC配置代码,需要配置文件上传处理器,我的是springmvc-servlet.xml:

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>

JS及表单部分,功能单一,没有使用其它的js,除了jqueryspringmvc下使用formdata异步ajax上传图片,标红的部分是我遇到的问题(在水狐提示uncaught exception:out of memory,请求失败):


<script
src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>

function asyncUploadFile() {  var fd = new FormData(document.getElementById("form1"));  $.ajax({    url: "${pageContext.request.contextPath}/img/upload",    type: "POST",    data: fd,    dataType:"json",    processData: false,  // 告诉jQuery不要去处理发送的数据    contentType: false ,  // 告诉jQuery不要去设置Content-Type请求头    success:function(data){      alert(data.msg);    },    error:function(){      alert("error");    }  });}
<form id="form1" method="post" enctype="multipart/form-data">
  <input type="file" name="pic_up"/>  <button type="button" onclick="asyncUploadFile()">异步上传图片测试</button></form>




Controller部分:

@RequestMapping("/upload")
public void upload(HttpServletRequest request, HttpServletResponse response, @RequestParam MultipartFile pic_up) throws Exception {
String orginalName = pic_up.getOriginalFilename();
if (pic_up != null && orginalName != null && orginalName.length() > 0) {
String imgDir = request.getServletContext().getRealPath("attached/image");
String suffix = orginalName.split("\\.")[1];
String imgName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + new Random().nextInt(1000) + "." + suffix;
String imgurl = "/attached/image/" + imgName;
File file = new File(imgDir, imgName);
pic_up.transferTo(file);
JSONObject obj = new JSONObject();
obj.put("code",1);
obj.put("msg","上传成功");
response.getWriter().write(JSON.toJSONString(obj));
}
}


控制台DEBUG,显示上传成功:

DEBUG [http-bio-80-exec-6] - Multipart file 'pic_up' with original filename [1(1).jpg], stored at [C:\Users\Administrator\.IntelliJIdea2016.1\system\tomcat\tomcat_jiumu_gps\work\Catalina\localhost\_\upload_6b5fac79_154bcd2cb8e__7fd4_00000000.tmp]: moved to [D:\_workspace\jiumu_gps\out\artifacts\web_war_exploded\attached\image\20160517114706_110.jpg]