SpringMvc+Angularjs 实现多文件批量上传
程序员文章站
2024-03-04 17:11:47
springmvc代码
jar包
commons-fileupload
commons-io
spring-mvc.xml配置
springmvc代码
jar包
commons-fileupload
commons-io
spring-mvc.xml配置
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver"> <property name="defaultencoding" value="utf-8" /> </bean>
controller
@requestmapping(value = "api/v1/upload", method = requestmethod.post, produces = mediatype.application_json_value) @responsebody public map upload (@requestparam(value = "files") multipartfile [] files, @requestparam(value = "id") string id, httpservletrequest request, httpservletresponse response) { map res = new hashmap(); try { log.info("upload>>>>>id:{}", id); if (files!=null) { for (multipartfile file:files) { log.info("filename:{}", file.getoriginalfilename()); } } } catch (exception e) { log.error("upload>>>>异常:{}", e.tostring()); } log.info("upload>>>>返回结果:{}", res); return res; }
保存到本地
// copy file public boolean copyfile (multipartfile tempfile, string filepath) { boolean res = false; try { file file = new file(filepath); if (!file.getparentfile().exists()) { file.getparentfile().mkdirs(); } // 将文件拷贝到当前目录下 tempfile.transferto(file); res = true; } catch (exception e) { log.info("copyfile>>>>异常:{}", e.tostring()); } return res; }
angularjs代码
<!doctype html> <html> <head> <meta charset="utf-8"> <script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> </head> <body> <div ng-app="myapp" ng-controller="uploadctrl"> <p><input type="file" multiple="multiple" name="files"></p> <p><input type="text" name="id" ng-model="id"></p> <p><input type="button" value="提交" ng-click="submit()"></p> </div> <script> var app = angular.module('myapp', []); app.controller('uploadctrl', ["$scope", "$http", function($scope, $http) { $scope.submit = function () { var fd = new formdata(); var files = document.queryselector('input[name="files"]').files; for (var i=0; i<files.length; i++) { fd.append("files", files[i]); } fd.append("id", $scope.id); $http({ method:'post', url : '/project/api/v1/upload', data: fd, headers: {'content-type':undefined}, transformrequest: angular.identity }).success(function (response) { console.log(response.data); }).error(function () { }); } }]); </script> </body> </html>
form表单提交
<form action="/project/api/v1/upload" method="post" enctype="multipart/form-data"> <p><input type="text" name="id" /></p> <p><input type="file" multiple="multiple" id="files" name="files" /></p> <p><input type="submit" value="submit" /></p> </form>
以上所述是小编给大家介绍的springmvc+angularjs 实现多文件批量上,希望对大家有所帮助
下一篇: php解决DOM乱码的方法示例代码