2017-10-06 163 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; 
};