Multipart request with AngularJS

后端 未结 5 1365
说谎
说谎 2020-12-30 02:20

I have an API endpoint to which I must send a multipart HTTP request, composed of two parts, file (a file system file) and data (a JSON object).

相关标签:
5条回答
  • 2020-12-30 02:30

    Have you tried something like this:

    $httpProvider.defaults.transformRequest = function(data) {
      if (data === undefined){
        return data;
      }
    
      var formData = new FormData();
      for (var key in data){
        if(typeof data[key] == 'object' && !(data[key] instanceof File)){
          formData.append(key, JSON.stringify(data[key]));
        }else{
          formData.append(key, data[key]);
        }
      }
      return formData;
    };
    
    0 讨论(0)
  • 2020-12-30 02:32

    The easiest way to upload files in Angular:

    var fd = new FormData();
    fd.append('file', file);
    fd.append('data', 'string');
    $http.post(uploadUrl, fd, {
       transformRequest: angular.identity,
       headers: {'Content-Type': undefined}
    })
    .success(function(){
    })
    .error(function(){
    });
    

    Absolutely essential are the following two properties of the config object:

    transformRequest: angular.identity
    

    overrides Angular's default serialization, leaving our data intact.

    headers: {'Content-Type': undefined }
    

    lets the browser detect the correct Content-Type as multipart/form-data, and fill in the correct boundary.

    Nothing else worked for me! Courtesy of Lady Louthan's wonderful blogpost.

    0 讨论(0)
  • 2020-12-30 02:39

    what i did to solve this was.

    var formData = new FormData(document.getElementById('myFormId'));
    

    then in my service

                    var deferred = $q.defer();
                    $http.post('myurl', formData, {
                        cache: false,
                        contentType: false,
                        processData: false,
                    })
                        .success(function (response) {
                            deferred.resolve(response);
                        })
                        .error(function (reject) {
                            deferred.reject(reject);
                        });
                    return deferred.promise;
    
    0 讨论(0)
  • 2020-12-30 02:52

    I just solve exactly the same problem.

    After some tests, I had this situation that you've described:

    Basically what happens is with 1) the correct values are set in the multiparts, but the contentType's are not set. With 2) the contentType's are set, but not the values for the multiparts.

    To fix this problem, I had to use Blob and Post Ajax instead of $http Post.

    It seems that $http does not work correctly in this case.

    Code:

        var formData = new FormData();
    
        var blobId = new Blob([100], { 'type':'text/plain' });
        formData.append('testId', blobId);
    
        var blobImage = fileService.base64ToBlob(contentToDecode, 'image/jpeg');
        formData.append('file', blobImage, 'imagem' + (i + 1) + '.jpg');
    

    Request:

        $.ajax({
          url: url,
          data: formData,
          cache: false,
          contentType: false,
          processData: false,
          type: 'POST',
          success: function(response) {
            deferred.resolve(response);
            $rootScope.requestInProgress = false;
          },
          error: function(error) {
            deferred.reject(error);
            $rootScope.requestInProgress = false;
          }
        });
    
    0 讨论(0)
  • 2020-12-30 02:54

    You can use https://github.com/danialfarid/ng-file-upload/.

    In this file uploader, there is a provision for sending the file and data (in JSON format) separately as you mentioned in your question above.

    For Ex:-

    var upload = $upload.upload({
                     url: url,
                     file: file,
                     method: 'POST' or 'PUT', default POST,
                     headers: {'Content-Type': 'multipart/form-data'}, // only for html5
                     fileName: 'doc.jpg',
                     fileFormDataName: 'myFile',
                     data: {'data': model}
                 });
    

    In the above code, you can send either a POST or PUT request with 'multipart/form-data', file and data object as JSON separately.

    For more information you can visit the above link and look at the ReadMe.md of the plug-in.

    I know that my approach is a bit different from the one that you are currently following, but the objective is same.

    0 讨论(0)
提交回复
热议问题