我正在将一些元素上传到S3。我在此链接中使用了相同的示例:
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
此时,它可以工作,但现在,我需要捕获上传文件的URL。我怎样才能做到这一点?我是新上传的文件:/
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
提前完成。
答案 0 :(得分:0)
使用异步API创建服务时,返回API返回的承诺非常重要:
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
̶v̶a̶r̶ ̶f̶d̶ ̶=̶ ̶n̶e̶w̶ ̶F̶o̶r̶m̶D̶a̶t̶a̶(̶)̶;̶
̶f̶d̶.̶a̶p̶p̶e̶n̶d̶(̶'̶f̶i̶l̶e̶'̶,̶ ̶f̶i̶l̶e̶)̶;̶
//RETURN the promise
͟r͟e͟t͟u͟r͟n͟ $http.post(uploadUrl, ̶f̶d̶,̶ ͟f͟i͟l͟e͟,͟ {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(response) {
return response.data;
}).catch(function(response) {
console.log("ERROR: ", response.status;
//IMPORTANT
throw response;
});
}
}]);
此外,如果服务器支持它,则直接上传文件会更有效。 formData API使用内容类型multipart/form-data
和base64编码,增加了33%的额外开销。
在控制器中,从返回的承诺中提取数据:
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
var promise = fileUpload.uploadFileToUrl(file, uploadUrl);
promise.then(function(data) {
console.log(data);
});
return promise;
};