2017-10-06 53 views
0

我上传了一些元素到S3。我使用的是相同的例子此链接里面:从文件上传文章中获取网址

JsFiddle

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(){ 
     }); 
    } 
}]); 

Thanx提前。

+0

的'.success'和'.error'方法弃用。有关更多信息,请参阅[为什么不推荐使用角度$ http成功/错误方法?从V1.6删除?](https://stackoverflow.com/questions/35329384/why-are-angular-http-success-error-methods-deprecated-removed-from-v1-6/35331339#35331339)。 – georgeawg

回答

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-database64编码,增加了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; 
};