AngularJS如何上传多部分表单数据和文件?

AngularJS如何上传多部分表单数据和文件?,第1张

AngularJS如何上传多部分表单数据和文件?

首先

  1. 您无需对结构进行任何特殊更改。我的意思是:html输入标签。
    <input accept="image/*" name="file" ng-value="fileToUpload"value="{{fileToUpload}}" file-model="fileToUpload"set-file-data="fileToUpload = value;" type="file" id="my_file" />

1.2创建自己的指令,

    .directive("fileModel",function() {        return { restrict: 'EA', scope: {     setFiledata: "&" }, link: function(scope, ele, attrs) {     ele.on('change', function() {         scope.$apply(function() {  var val = ele[0].files[0];  scope.setFileData({ value: val });         });     }); }        }    })
  1. 在带有$ httpProvider的模块中,添加具有multipart / form-data的依赖项(如Accept,Content-Type等)。(建议是接受json格式的响应)例如:

$ httpProvider.defaults.headers.post [‘Accept’] =’application / json,text /
javascript’; $ httpProvider.defaults.headers.post [‘Content-Type’]
=’multipart / form-data; charset = utf-8’;

  1. 然后在控制器中创建单独的函数来处理表单提交调用。例如下面的代码:

  2. 在服务函数中,要有目的地处理“ responseType”参数,以便服务器不应抛出“ byteerror”。

  3. transformRequest,用于修改带有附加身份的请求格式。

  4. withCredentials:false,用于HTTP认证信息。

    in controller:      // pre this accordingly, so that your file object       // will be picked up in service call below.      fileUpload.uploadFileToUrl(file);     in service:      .service('fileUpload', ['$http', 'ajaxService',        function($http, ajaxService) {          this.uploadFileToUrl = function(data) { var data = {}; //file object  var fd = new FormData(); fd.append('file', data.file); $http.post("endpoint server path to whom sending file", fd, {     withCredentials: false,     headers: {       'Content-Type': undefined     },     transformRequest: angular.identity,     params: {       fd     },     responseType: "arraybuffer"   })   .then(function(response) {     var data = response.data;     var status = response.status;     console.log(data);     if (status == 200 || status == 202) //do whatever in success     else // handle error in  else if needed    })   .catch(function(error) {     console.log(error.status);     // handle else calls   });          }        }      }])    <script src="//unpkg.com/angular/angular.js"></script>


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4897311.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存