$http.post: Large files do not work

后端 未结 3 650
甜味超标
甜味超标 2020-12-21 07:13

I am trying to upload files through my web app using the following code.

View:

  
3条回答
  •  庸人自扰
    2020-12-21 07:40

    Avoid using the FormData API when Uploading Large Files1

    The FormData API encodes data in base64 which add 33% extra overhead.

    Instead of sending FormData, send the file directly:

    app.service('fileUpload', function ($http) {
        this.uploadFileToUrl = function (url, file) {
            ̶v̶a̶r̶ ̶f̶d̶ ̶=̶ ̶n̶e̶w̶ ̶F̶o̶r̶m̶D̶a̶t̶a̶(̶)̶;̶
            ̶f̶d̶.̶a̶p̶p̶e̶n̶d̶(̶'̶f̶i̶l̶e̶'̶,̶ ̶f̶i̶l̶e̶)̶;̶
            ̶r̶e̶t̶u̶r̶n̶ ̶$̶h̶t̶t̶p̶.̶p̶o̶s̶t̶(̶u̶r̶l̶,̶ ̶f̶d̶,̶ ̶{̶
            return $http.post(url, file, {
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined }
            });
        };
    });
    

    When the browser sends FormData, it uses 'Content-Type': multipart/formdata and encodes each part using base64.

    When the browser sends a file (or blob), it sets the content type to the MIME-type of the file (or blob). It puts the binary data in the body of the request.


    How to enable to work with ng-model2

    Out of the box, the ng-model directive does not work with input type="file". It needs a directive:

    app.directive("selectNgFile", function() {
      return {
        require: "ngModel",
        link: function postLink(scope,elem,attrs,ngModel) {
          elem.on("change", function(e) {
            var files = elem[0].files[0];
            ngModel.$setViewValue(files);
          })
        }
      }
    });
    

    Usage:

    
    

提交回复
热议问题