50

我在python中有以下请求

import requests, json, io

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

fi = {'file': ('file', open(file) )}
r = requests.post("http://192.168.1.1:8080" + url, data=payload, files=fi, cookies=cookie)
print(r.text)

它将文件和表单字段发送到后端。如何使用 Angular $http 做同样的事情(发送文件 + 表单字段)。目前,我确实喜欢这样,但也不确定如何发送文件。

var payload = {"Name":"abc"};
$http.post('/test', payload)
    .success(function (res) {
    //success
});
4

8 回答 8

136

当必须同时上传文件和发送用户令牌信息时,我遇到了类似的问题。transformRequest随着成型FormData帮助:

        $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) {

        });

为了获取文件$scope.file,我使用了自定义指令:

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:

<input type="file" file="file" required />
于 2014-08-12T12:14:05.167 回答
24

在发布到 Web.Api 应用程序时,我无法让 Pavel 的答案正常工作。

问题似乎与删除标题有关。

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

为了确保允许浏览器默认 Content-Type 和边界参数,我需要将 Content-Type 设置为 undefined。使用 Pavel 的示例,从未设置边界,从而导致 400 HTTP 异常。

关键是删除删除上面显示的标题的代码,并将标题内容类型手动设置为 null。从而允许浏览器设置属性。

headers: {'Content-Type': undefined}

这是一个完整的例子。

$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;
            }
于 2016-07-28T15:36:04.297 回答
5

我最近写了一个支持原生多文件上传的指令。我创建的解决方案依赖于一项服务来填补您在 $http 服务中发现的空白。我还包含了一个指令,它为您的 Angular 模块提供了一个简单的 API,用于发布文件和数据。

示例用法:

<lvl-file-upload
    auto-upload='false'
    choose-file-button-text='Choose files'
    upload-file-button-text='Upload files'
    upload-url='http://localhost:3000/files'
    max-files='10'
    max-file-size-mb='5'
    get-additional-data='getData(files)'
    on-done='done(files, data)'
    on-progress='progress(percentDone)'
    on-error='error(files, type, msg)'/>

你可以在 github 上找到代码,在我的博客上找到文档

处理 Web 框架中的文件取决于您,但我创建的解决方案提供了将数据传输到服务器的角度接口。您需要编写的角度代码是响应上传事件

angular
    .module('app', ['lvl.directives.fileupload'])
    .controller('ctl', ['$scope', function($scope) {
        $scope.done = function(files,data} { /*do something when the upload completes*/ };
        $scope.progress = function(percentDone) { /*do something when progress is reported*/ };
        $scope.error = function(file, type, msg) { /*do something if an error occurs*/ };
        $scope.getAdditionalData = function() { /* return additional data to be posted to the server*/ };

    });
于 2013-09-12T13:32:08.137 回答
3

请看看我的实现。您可以将以下函数包装到服务中:

function(file, url) {
  var fd = new FormData();

  fd.append('file', file);

  return $http.post(url, fd, {
    transformRequest: angular.identity,
    headers: { 'Content-Type': undefined }
  });
}

请注意,该file参数是Blob. 如果您有base64文件的版本 - 它可以很容易地更改为Blob

fetch(base64).then(function(response) {
  return response.blob(); 
}).then(console.info).catch(console.error);
于 2017-06-21T15:39:46.010 回答
2

您也可以使用 HTML5 上传。您可以使用此AJAX 上传器。

JS代码基本上是:

  $scope.doPhotoUpload = function () {
    // ..
    var myUploader = new uploader(document.getElementById('file_upload_element_id'), options);
    myUploader.send();
    // ..
  }

从 HTML 输入元素中读取

<input id="file_upload_element_id" type="file" onchange="angular.element(this).scope().doPhotoUpload()">
于 2013-05-10T16:11:50.253 回答
2

这是我的解决方案:

// Controller
$scope.uploadImg = function( files ) {
  $scope.data.avatar = files[0];
}

$scope.update = function() {
  var formData = new FormData();
  formData.append('desc', data.desc);
  formData.append('avatar', data.avatar);
  SomeService.upload( formData );
}


// Service
upload: function( formData ) {
  var deferred = $q.defer();
  var url = "/upload"	;
  
  var request = {
    "url": url,
    "method": "POST",
    "data": formData,
    "headers": {
      'Content-Type' : undefined // important
    }
  };

  console.log(request);

  $http(request).success(function(data){
    deferred.resolve(data);
  }).error(function(error){
    deferred.reject(error);
  });
  return deferred.promise;
}


// backend use express and multer
// a part of the code
var multer = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '../public/img')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + '.jpg');
  }
})

var upload = multer({ storage: storage })
app.post('/upload', upload.single('avatar'), function(req, res, next) {
  // do something
  console.log(req.body);
  res.send(req.body);
});
<div>
  <input type="file" accept="image/*" onchange="angular.element( this ).scope().uploadImg( this.files )">
  <textarea ng-model="data.desc" />
  <button type="button" ng-click="update()">Update</button>
</div>

于 2017-04-25T11:19:05.930 回答
0

您可以查看http://ngmodules.org/modules/ngUpload的其他解决方案,如此处讨论的 angularjs 文件上传器集成

于 2013-05-10T14:27:05.400 回答
0

在我的解决方案中,我有

$scope.uploadVideo = function(){
    var uploadUrl = "/api/uploadEvent";


    //obj with data, that can be one input or form
    file = $scope.video;
    var fd = new FormData();


    //check file form on being
    for (var obj in file) {
        if (file[obj] || file[obj] == 0) {
            fd.append(obj, file[obj]);
        }
    }

    //open XHR request
    var xhr = new XMLHttpRequest();


    // $apply to rendering progress bar for any chunking update
    xhr.upload.onprogress = function(event) {
        $scope.uploadStatus = {
            loaded: event.loaded,
            total:  event.total
        };
        $scope.$apply();
    };

    xhr.onload = xhr.onerror = function(e) {
        if (this.status == 200 || this.status == 201) {

            //sucess

            $scope.uploadStatus = {
                loaded: 0,
                total:  0
            };


            //this is for my solution
            $scope.video = {};
            $scope.vm.model.push(JSON.parse(e.currentTarget.response));
            $scope.$apply();

        } else {
           //on else status
        }
    };

    xhr.open("POST", uploadUrl, true);

    //token for upload, thit for my solution
    xhr.setRequestHeader("Authorization", "JWT " + window.localStorage.token);


    //send
    xhr.send(fd); 
};

}

于 2016-08-01T22:48:20.553 回答