小编典典

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

angularjs

我是angular.js的初学者,但是对基础知识有很好的了解。

我要做的是上传文件和一些表单数据作为多部分表单数据。我读到这不是angular的功能,但是3rd
party库可以做到这一点。我已经通过git克隆了angular-file-upload,但是仍然无法发布简单的表单和文件。

有人可以提供如何执行此操作的示例,html和js吗?


阅读 260

收藏
2020-07-04

共1个答案

小编典典

首先

  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:



      // code 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>
2020-07-04