$http post multipart/form-data boundary not set

2019-09-14 11:12发布

问题:

I am setting the boundary for the below post call but on chrome the boundary looks different from the one I set. how do I get my custom boundary "--test" to show up on the request payload?

    var url = '/site/apkUpload';
    var deferred = $q.defer();
    console.log(formdata);
    $http.post(url, formdata, {
        processData: false,
        headers: {'Content-Type': "multipart/form-data;  charset=utf-8; boundary='--test'",
            'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            'x-access-token': token,
            'cache-control': 'max-age=0'}
    })
        .success(function (response) {
            deferred.resolve(response);
        })
        .error(function (reject) {
            deferred.reject(reject);
        });
    return deferred.promise;

Request payload on chrome:

------WebKitFormBoundaryB5LjM2a6Qly3Xruj Content-Disposition: form-data; name="packageName"

helo1 ------WebKitFormBoundaryB5LjM2a6Qly3Xruj Content-Disposition: form-data; name="name"

......

Thanks a lot!

回答1:

I can interpret your question in 2 ways:

  1. You are talking about why you are not getting ------WebKitFormBoundaryB5LjM2a6Qly3Xruj in the POST request header, which you are getting in the request payload. I had the same issue while sending a multi-part formdata using $http.post (also I was using FormData).The solution to this is using $http(config).To my understanding $http.post underlying uses $http() itself to generate XMLHttpRequest object, which should run the multipart/form-data encoding algorithm to set the multipart boundary in payload and the header as well. In $http.post, it seems whenever you give a custom config object it overwrites the header generated by the algorithm. This answer is also helpful.
  2. If you just want to add a custom multipart boundary in the content-header, then you can achieve that by add a tranformRequest function in the config object:

    var url = '/site/apkUpload';
    var deferred = $q.defer();
    console.log(formdata);
    $http.post(url, formdata, {
        processData: false,
        transformRequest: function (data, headers) {
            var boundary = yourCustomLogic();
            headers()['Content-Type'] = 'multipart/form-data;charset=utf-
            8;boundary=' + boundary;
        },
        'Accept': ...,
        'x-access-token': token,
        'cache-control': 'max-age=0'
    })
    .success( function () {...});