【发布时间】: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