Multipart request with AngularJS

后端 未结 5 1383
说谎
说谎 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: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.

提交回复
热议问题