java相关:SpringMVC使用MultipartFile 实现异步上传方法介绍
发布于 2021-1-6|
复制链接
摘记: 目的是实现异步上传
1.添加pom依赖
添加pom依赖,因为用的ajax,数据需要转成json的格式进行传输,所以还有加入一个JSON jar包:
```xhtml
commons-fileupload ..
目的是实现异步上传1.添加pom依赖
添加pom依赖,因为用的ajax,数据需要转成json的格式进行传输,所以还有加入一个JSON jar包:
```xhtml
commons-fileupload
commons-fileupload
1.3.1
commons-logging
commons-logging
1.2
com.alibaba
fastjson
1.1.37
```
2.修改配置文件
applicationContext.xml里面需要加上:
```xhtml
```
3.前端页面上
前端页面:
```xhtml
文件
提交
```
需要加入的JS:
```xhtml
```
JS方法:
```javascript
$(function() {
$("#doSave")
.click(
function() {
$("#uploadForm")
.ajaxSubmit(
{
type : 'post',
url : "/tmpInfo/method2.do",
//data: //注意只要是写在表单里面的,都不需要加这个属性。在controller中可以根据@RequestParam String str获取到属性值。
contentType : "application/x-www-form-urlencoded; charset=utf-8",
success: function(data) {
//接受到的data还只是一个字符串,需要转成json对象
var obj = JSON.parse(data);
if(obj.flag==true){
alert("上传成功");
}else{
alert("error");
}
},
error: function (data)//服务器响应失败处理函数
{
alert("出错");
}
});
});
});
```
controller代码:
```java
@RequestMapping("/method2")
@ResponseBody
public String method2(@RequestParam MultipartFile file,
@RequestParam String messageContent ) {
//多个参数的话只要多个@RequestParam即可,注意参数名要和表单里面的属性名一致
JSONObject json =new JSONObject();
System.out.println(messageContent);
String orgiginalFileName = "";
int m =new Random().nextInt(100)+10;
System.out.println("m="+m);
String path="D:/"+m+"b.txt";
try {
File newFile =new File(path);
file.transferTo(newFile);
String fileName = file.getName();
InputStream inputStream = file.getInputStream();
String content = file.getContentType();
orgiginalFileName = file.getOriginalFilename();
System.out.println("fileName: "+fileName+", inputStream: "+ inputStream
+"\r\n content: "+content+", orgiginalFileName: ="+ orgiginalFileName
+"\r\n projectName: ");
} catch (IOException e) {
e.printStackTrace();
}
json.put("flag", true);
json.put("message", "success");
System.out.println(json.toJSONString());
return json.toJSONString();
}
```