1,配置springmvc.xml
<!-- 文件上传配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小限制,上限为10MB,单位为字节 -->
<property name="maxUploadSize">
<value>10485760</value>
</property>
<!-- 请求编码格式,必须和JSP的pageEncoding属性一致,以便正确读取表单内容,默认为ISO-8859-1 -->
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
2,页面
Request Method:POST,Request URL:http://localhost:8082/upload.do
3,后端
主要根据@RequestParam("file") MultipartFile file,获取页面传来的file
@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) throws Exception {
String realPath="E:/temp_test/";
//获取文件名称
String fileName = file.getOriginalFilename();
realPath=realPath + fileName;
//写入本地磁盘
InputStream is = file.getInputStream();
byte[] bs = new byte[1024];
int len;
OutputStream os = new FileOutputStream(new File(realPath));
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
os.close();
is.close();
JSONObject json=new JSONObject();
JSONObject jdata=new JSONObject();
json.put("code",0);
json.put("msg","成功");
jdata.put("src",realPath);
jdata.put("title",fileName);
json.put("data",jdata);
return json.toString();
}
我上面返回的组装json格式主要是:我测试时用layui中富文本中的图片上传要返回固定格式。