简体   繁体   中英

Adding Authentication token to file upload in angular 2

How can i add authentication token to the file upload service? When i login in my application, i am able to retrieve the token from the backend but i am having a hard time as to how to add it the to file service. When i try to upload a file, it get an error saying "token_not_provided". As it is in my service, i have added the authentication token in my header so whenever i make a request, the server is aware of the user at hand. But with the file submission, i have no idea of how to append the authentication token to the file service

 @Component({
        providers:[AuthenticationService]
    })
    @Injectable()
    export class FileUploadService {
       public progress$;
      public progressObserver;
        public progress : number;
        public token: string;
        public headers:string;


        constructor (private auth:AuthenticationService) {
            this.progress$ = Observable.create(observer => {
                this.progressObserver = observer
            }).share();
        }

         makeFileRequest (url: string, params: string[], files: File[]) {
            return Observable.create(observer => {
                let formData: FormData = new FormData(),
                    xhr: XMLHttpRequest = new XMLHttpRequest();

                for (let i = 0; i < files.length; i++) {
                    formData.append("uploads[]", files[i], files[i].name);
                }

                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            observer.next(JSON.parse(xhr.response));
                            observer.complete();
                        } else {
                            observer.error(xhr.response);
                        }
                    }
                };

                xhr.upload.onprogress = (event) => {

                    this.progress = Math.round(event.loaded / event.total * 100);

                    this.progressObserver.next(this.progress);
                };

                xhr.open('POST', url, true);
                xhr.setRequestHeader(this.headers, this.auth.token);//modified

              xhr.send(formData);


            });
        }
    }

//service
updateFood(food:any) {
        const body = JSON.stringify(food);
        const headers = new Headers({ 'Authorization': 'Bearer ' + this.authenticationService.token });
        return this.http.put('http://localhost:9000/, body, {headers: headers})
            .map((data:Response) => data.json());
    }

Somewhere between your xhr.open and xhr.close you can append headers

xhr.setRequestHeader(header, value);

See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader for more detailed documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM