Lez Yeoh
Lez Yeoh

Reputation: 350

How to Upload file to S3 using Angular/Node ng-file-upload

Unable to get file upload to S3 working. That being said, I know the problem is on my end.

At the moment I can upload a file to S3 using: https://s3.amazonaws.com/doc/s3-example-code/post/post_sample.html

Now if I copy and paste the form to my app, and just Post the form, it works.

Next step I'm doing is to move the hardcoded values into the Angular controller to attempt uploading the file through there before implementing server side creation of policy and signature, although it doesn't seem to work.

Error I'm getting is the Authorization: Bearer issue.

After reading it, I've tried setting Authorization to undefined, and that still isn't working and I'm at a loss.

Any help would be appreciated.

Code below:

var mypolicy = "HardcodedPolicy;
var mysignature = "HardcodedSignature";

var s3url = "https://myBucket.s3.amazonaws.com/";

Upload.upload({
  url: s3url,
  method: 'POST',
  headers: {
    'Authorization': undefined
  },
  data: {
    key: 'testfile.txt',
    acl: 'public-read',
    "Content-Type": 'text/plain',
    AWSAccessKeyId: 'XXX',
    policy: mypolicy,
    signature: mysignature,
    file: uploadfile
  }
}).error(function(err) {
  console.log("err: ", err);
})

Upvotes: 0

Views: 486

Answers (1)

Tim Cullen
Tim Cullen

Reputation: 23

I have spent ages trying to find a solution to this and finally got it to work. I hope this solution helps others. In my case the problem was caused by our app using jwt tokens to authenticate users whenever they make calls to our api. The code which added the token was in an angular factory like this:

    
App.factory('authInterceptor', ['$rootScope', '$q', '$cookieStore', '$location','$window',
        function ($rootScope, $q, $cookieStore, $location, $window) {
        return {
            // Add authorization token to headers
            request: function (config) {
                config.headers = config.headers || {};
                if ($cookieStore.get('token')) { 
             config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
                }
                return config;
            }
}]);

The solution we used was to amend the conditon statement so the authorization header was only added if required. We changed the 'if' statement to

if ($cookieStore.get('token') && config.url != "https://yourbucket.s3.amazonaws.com/")

Hope this helps someone else.

Upvotes: 1

Related Questions