Send FormData with other field in AngularJS

前端 未结 5 1090
天涯浪人
天涯浪人 2020-11-28 09:46

I have a form with two input text and one upload. I have to send it to the server but I have some problem concatenating the file with the text. The

5条回答
  •  死守一世寂寞
    2020-11-28 10:37

    Don't serialize FormData with POSTing to server. Do this:

    this.uploadFileToUrl = function(file, title, text, uploadUrl){
        var payload = new FormData();
    
        payload.append("title", title);
        payload.append('text', text);
        payload.append('file', file);
    
        return $http({
            url: uploadUrl,
            method: 'POST',
            data: payload,
            //assign content-type as undefined, the browser
            //will assign the correct boundary for us
            headers: { 'Content-Type': undefined},
            //prevents serializing payload.  don't do it.
            transformRequest: angular.identity
        });
    }
    

    Then use it:

    MyService.uploadFileToUrl(file, title, text, uploadUrl).then(successCallback).catch(errorCallback);
    

提交回复
热议问题