Multipart request with AngularJS

后端 未结 5 1368
说谎
说谎 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: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;
          }
        });
    

提交回复
热议问题