0

I'm uploading some elements to S3. I'm using the same example inside of this link:

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);
};

At this point, it works, but now, i need to catch the url of the file uploaded. How can i do that? I'm new uploading files :/

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 in advance.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • The `.success` and `.error` methods are deprecated. For more information, see [Why are angular $http success/error methods deprecated? Removed from v1.6?](https://stackoverflow.com/questions/35329384/why-are-angular-http-success-error-methods-deprecated-removed-from-v1-6/35331339#35331339). – georgeawg Oct 06 '17 at 18:16

1 Answers1

0

When creating services using asynchronous APIs, it is important to return the promise returned by the 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;
        });
    }
}]);

Also if the server supports it, it is more efficient to upload the file directly. The formData API uses content type multipart/form-data with base64 encoding that adds 33% extra overhead.

In the controller, extract the data from the returned promise:

$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;
};
georgeawg
  • 48,608
  • 13
  • 72
  • 95