AngularJS上传文件的示例代码
程序员文章站
2022-05-28 20:38:17
使用angularjs上传文件
前台是angular页面
后台使用springboot/spirngmvc
上传文件
html
&...
使用angularjs上传文件
- 前台是angular页面
- 后台使用springboot/spirngmvc
上传文件
html
<div> <input id="fileupload" type="file" /> <button ng-click="uploadfile()">上传</button> </div>
js
$scope.upload = function(){ var form = new formdata(); var file = document.getelementbyid("fileupload").files[0]; form.append('file', file); $http({ method: 'post', url: '/upload', data: form, headers: {'content-type': undefined}, transformrequest: angular.identity }).success(function (data) { console.log('upload success'); }).error(function (data) { console.log('upload fail'); }) }
注意:
- angularjs默认的'content-type'是application/json ,通过设置'content-type': undefined,这样浏览器不仅帮我们把content-type 设置为 multipart/form-data,还填充上当前的boundary,
- 如果手动设置为:'content-type': multipart/form-data,后台会抛出异常:the request was rejected because no multipart boundary was found
- boundary 是随机生成的字符串,用来分隔文本的开始和结束
- 通过设置 transformrequest: angular.identity ,anjularjs transformrequest function 将序列化我们的formdata object,也可以不添加
后台
@requestmapping("/upload") public void uploadfile(@requestparam(value = "file" , required = true) multipartfile file) { //deal with file }
注意
文件必须通过@requestparam注解来获取,且需指定value才能获取到
这样就完成了上传文件
上传文件的同时传递其他参数
html
<div> <input id="fileupload" type="file" /> <button ng-click="ok()">上传</button><br> <input ng-model="user.username" /> <input ng-model="user.password" /> </div>
js
$scope.ok = function () { var form = new formdata(); var file = document.getelementbyid("fileupload").files[0]; var user =json.stringify($scope.user); form.append('file', file); form.append('user',user); $http({ method: 'post', url: '/adduser', data: form, headers: {'content-type': undefined}, transformrequest: angular.identity }).success(function (data) { console.log('operation success'); }).error(function (data) { console.log('operation fail'); }) };
注意
需要将object转为string后在附加到form上,否则会直接被转为字符串[object,object]
后台
@requestmapping("/upload") public map<string, object> upload(@requestparam(value = "file") multipartfile file, @requestparam(value = "user", required = true) string user) { try (fileinputstream in = (fileinputstream) headimg.getinputstream(); fileoutputstream out = new fileoutputstream("filepathandname")) { //将json对象解析为usermodel对象 objectmapper objectmapper = new objectmapper(); usermodel usermodel = objectmapper.readvalue(user, usermodel.class); //保存文件到filepathandname int hasread = 0; byte[] bytes = new byte[1024]; while ((hasread = in.read(bytes)) > 0) { out.write(bytes, 0, hasread); } } catch (ioexception e) { e.printstacktrace(); } }
注意
objectmapper为com.fasterxml.jackson.databind.objectmapper
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: vue组件从开发到发布的实现步骤
下一篇: WCF:一个棘手的问题