2017-10-06 10 views
0

일부 요소를 S3에 업로드하고 있습니다. 작동,이 시점에서파일 업로드 게시글에서 URL 가져 오기

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

고지

+0

은'.success'와는'.error' 방법이 사용되지 않습니다. 자세한 내용은 [왜 $ $ 성공/오류 메서드가 더 이상 사용되지 않습니다? 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-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; 
};