Search code examples
angularng2-file-uploaddevise-token-auth

How do I use ng2-file-upload with devise token auth?


I am currently trying to use the ng2-file-upload along with devise token auth.: https://devise-token-auth.gitbook.io/devise-token-auth/conceptual. File uploader currently handles the http request directly and hence, I did not use with angular token rest api service class to upload objects: https://angular-token.gitbook.io/docs/session-management. Instead, I had to manually set the headers in line with the auth token.

URL = '/api/my_api'
public uploader: FileUploader = new FileUploader({ url: URL});
update_upload_parameters(){
  var uo: FileUploaderOptions = {};
  uo.headers = 
  [
   {name: 'access-token', value : localStorage.getItem("accessToken")}, 
   {name: 'client', value : localStorage.getItem("client")},
   {name: 'expiry', value : localStorage.getItem("expiry")},
   {name: 'token-type', value : localStorage.getItem("tokenType")},
   {name: 'uid', value : localStorage.getItem("uid")}
  ];
  this.uploader.setOptions(uo);

}

HTML file

<input id="file2" type="file" ng2FileSelect [uploader]="uploader" />

The upload itself goes through successfully, but post upload, I see that the access token in session does not work any longer. I assume this is because I use devise token auth which updates the token upon request and I am not settng this into my local storage. How can I retrieve and set the token from the response header manually into the local storage of the browser? (otherwise handled by angular token in normal requests)


Solution

  • Figured, works:

    this.uploader.onCompleteItem = (item:any, response:any, status:any, headers:any)=> {
            localStorage.setItem('accessToken', headers['access-token']);
            localStorage.setItem("expiry", headers['expiry']);
        };
    }