由于公司用的angular.js和SSM实现前后端分离,前端是以angular.js+Bootstrap编写,而为了兼容Spring MVC中用使用MultipartFile接收文件的写法,查找了很多资料,使这种写法能够正确使用,以下是使用的框架版本,可能会存在影响
- angular.js:1.4.7
- Spring MVC:4.1.4
1.angular.js和Spring MVC单文件上传
1.HTML
<input type="file" id="upload">
2.angular.js
function(index) {
var file = document.querySelector("#upload").files[0]
var fd = new FormData();
fd.append('file_id',$scope.arealist[index].file_id)
fd.append('location',$scope.arealist[index].location)
fd.append('file', file);
$http({
method : 'POST',
url : '/i/zone/updateZone',
data : fd,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
}).success(function(data) {
console.log(data)
});
};
这里要注意几点
- 使用id去获取文件,当使用$scope绑定的model获取文件时会失败,上传单文件要写下标[0]
- 请求必须为post,get无效,Controller中也要用post接收
3.Spring MVC
@RequestMapping(value = "/updateZone",method = RequestMethod.POST)
@ResponseBody
public Object updateZone(@RequestParam(value = "file_id", required = false) Integer file_id,
@RequestParam(value = "location", required = false) String location,
@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
//执行相应的操作
System.out.println(file.getOriginalFilename());
}
这里需要注意的是
- 用js中存入fd的相应的name去获取值和文件(这里写的比较繁琐,可以尝试使用实体去接收,但是name要和实体类属性对应,文件还是单独接收)
2.angular.js和Spring MVC多文件上传
仅需要修改HTML、angular、spring MVC部分代码,即可完成多文件上传功能
1.HTML
<input name="file" file-model="file" type="file" id="upload" multiple="multiple">
2.angular.js
function(){
var files = document.querySelector("#upload").files
var fd = new FormData();
for(var i=0; i<files.length; i++){
fd.append('files', files[i]);
}
fd.append("projectID" , $scope.projectID)
fd.append("zoneID" , $scope.AreaID)
fd.append("pointType" , pointType)
$http({
method : 'POST',
url : '/i/point/addPoint',
data : fd,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
}).success(function(data) {
console.log(data)
}
});
3.Spring MVC
@RequestMapping(value = "/updateZone",method = RequestMethod.POST)
@ResponseBody
public Object addPoint(@RequestParam(value = "file_id", required = false) Integer file_id,
@RequestParam(value = "location", required = false) String location,
@RequestParam(value = "files", required = false) MultipartFile[] files) throws IOException {
//执行相应的操作
for (MultipartFile file: files) {
System.out.println(file.getOriginalFilename());
}
}
PS:欢迎补充更好的方法和指出其中的不足