Angular.JS和Spring MVC之文件上传的兼容

来源:互联网 发布:sai mac 打不开 编辑:程序博客网 时间:2024/05/29 16:01

由于公司用的Angular和SSM实现前后端分离,前端是以Angular.JS+Bootstrap编写,而为了兼容Spring MVC中用使用MultipartFile接收文件的写法,查找了很多资料,使这种写法能够正确使用,以下是使用的框架版本,可能会存在影响

  1. Angular.JS:1.4.7
  2. 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)});};
这里要注意几点
  1. 使用id去获取文件,当使用$scope绑定的model获取文件时会失败,上传单文件要写下标[0]
  2. 请求必须为post,get无效,Controller中也要用post接收

3.Spring MVC

@RequestMapping(value = "/updateZone",method = RequestMethod.POST)@ResponseBodypublic 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());}

这里需要注意的是
  1. 用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").filesvar 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)@ResponseBodypublic 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:欢迎补充更好的方法和指出其中的不足
原创粉丝点击