Angularjs $http post file and form data

后端 未结 8 1132
广开言路
广开言路 2020-11-28 22:14

I have the below request in python

import requests, json, io

cookie = {}
payload = {\"Name\":\"abc\"}
url = \"/test\"
file = \"out/test.json\"

fi = {\'file         


        
8条回答
  •  春和景丽
    2020-11-28 22:55

    I was unable to get Pavel's answer working as in when posting to a Web.Api application.

    The issue appears to be with the deleting of the headers.

    headersGetter();
    delete headers['Content-Type'];
    

    In order to ensure the browsers was allowed to default the Content-Type along with the boundary parameter, I needed to set the Content-Type to undefined. Using Pavel's example the boundary was never being set resulting in a 400 HTTP exception.

    The key was to remove the code deleting the headers shown above and to set the headers content type to null manually. Thus allowing the browser to set the properties.

    headers: {'Content-Type': undefined}
    

    Here is a full example.

    $scope.Submit = form => {
                    $http({
                        method: 'POST',
                        url: 'api/FileTest',
                        headers: {'Content-Type': undefined},
                        data: {
                            FullName: $scope.FullName,
                            Email: $scope.Email,
                            File1: $scope.file
                        },
                        transformRequest: function (data, headersGetter) {
                            var formData = new FormData();
                            angular.forEach(data, function (value, key) {
                                formData.append(key, value);
                            });
                            return formData;
                        }
                    })
                    .success(function (data) {
    
                    })
                    .error(function (data, status) {
    
                    });
    
                    return false;
                }
    

提交回复
热议问题