Angularjs $http post file and form data

后端 未结 8 1145
广开言路
广开言路 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 23:16

    I had similar problem when had to upload file and send user token info at the same time. transformRequest along with forming FormData helped:

            $http({
                method: 'POST',
                url: '/upload-file',
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                data: {
                    email: Utils.getUserInfo().email,
                    token: Utils.getUserInfo().token,
                    upload: $scope.file
                },
                transformRequest: function (data, headersGetter) {
                    var formData = new FormData();
                    angular.forEach(data, function (value, key) {
                        formData.append(key, value);
                    });
    
                    var headers = headersGetter();
                    delete headers['Content-Type'];
    
                    return formData;
                }
            })
            .success(function (data) {
    
            })
            .error(function (data, status) {
    
            });
    

    For getting file $scope.file I used custom directive:

    app.directive('file', function () {
        return {
            scope: {
                file: '='
            },
            link: function (scope, el, attrs) {
                el.bind('change', function (event) {
                    var file = event.target.files[0];
                    scope.file = file ? file : undefined;
                    scope.$apply();
                });
            }
        };
    });
    

    Html:

    
    

提交回复
热议问题