【问题标题】:File object empty when sending to server ng-file-upload发送到服务器 ng-file-upload 时文件对象为空
【发布时间】:2016-07-20 17:02:42
【问题描述】:

我正在使用 ng-file-upload 将一个基本的单个文件上传到我的服务器。

我可以选择文件,查看我选择的文件名,并将文件对象 ($scope.myFiles[0]) 传递给我的角度服务。但是,当用文件填充我的 HTTP 数据属性时,在开发工具中检查 HTTP 请求时,文件是空对象。

控制器:

UploadService.upload( { data: { file: $scope.myFiles[0], 'category': $scope.selectedCategory}})
    .success(function (data) {
    ////
    ////

上传服务:

app.factory('UploadService', function ($http, $q) {
    return {
        upload: function (something) {
            console.log(something);

            return $http({
                method: 'POST',
                url: '/upload',
                data: something
            });
        }
    }
});

通过以上,在开发工具中检查 HTTP 请求,我看到:

Request Payload:
    {data: {file: {}, category: "Friend Card"}}
     data:
         {file: {}, category: "Friend Card"}
         category:"Friend Card"
         file:{}

查看 console.log(something) 的输出,我可以通过以下方式查看文件:

{
    $hashKey:"object:107"
    lastModified:1465716430000
    lastModifiedDate:Sun Jun 12 2016 08:27:10 GMT+0100 (BST)
    name:"Postcard.JPG"
    size:522622
    type:"image/jpeg"
    webkitRelativePath:""
}

已将函数更改为具有标头类型:

return $http({
            method: 'POST',
            url: '/upload',
            headers: {
                'Content-Type': something.data.file.type
            },
            data: {
                "file": something.data.file,
                "category": something.data.category
            }
        });

我可以在开发工具中看到:

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:48
Content-Type:image/jpeg
Cookie:_ga=GA1.1.2023678669.1463291637; _gat=1
Host:localhost:8585
Origin:http://localhost:8585
Referer:http://localhost:8585/pages/

特别是:Content-Type:image/jpeg 所以它看起来是正确的,但是文件仍然是空对象。

【问题讨论】:

  • 使用Upload.upload({url: ..., file: file})将文件上传到服务器而不是$http
  • @danial - 谢谢,但我不明白.. 而不是 http??你有例子吗?
  • 文档上有很多例子:Upload.upload({ method: 'POST', url: '/upload', data: something });

标签: javascript angularjs angularjs-scope jquery-file-upload ng-file-upload


【解决方案1】:

答案部分来自上面的danial...

ng-file-upload 库带有许多 API 和方法,可以注入到您的 Angular 应用程序中,其中之一是“上传”服务。

我将它注入到我的控制器中,并在此处遵循 jsFiddle:http://jsfiddle.net/danialfarid/maqbzv15/1118/

Upload.upload({
  url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
  data: {username: $scope.username, file: file},
});

【讨论】:

    猜你喜欢
    • 2018-05-28
    • 1970-01-01
    • 2014-11-16
    • 2019-02-04
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    相关资源
    最近更新 更多