2017-05-09 7 views
-1

I-Datei mit diesem Code zu laden versuchen:Angular 2 - Authentifizierung funktioniert nicht mit multipart/formdata

headers: Headers; 

    token = ''; 

    @ViewChild('fileInput') fileInput: ElementRef; 
    @ViewChild('profilePic') profilePic:ElementRef; 

    constructor(private element: ElementRef, private api: ApiService) {} 

    upload(fileToUpload:File) { 

    this.token = window.localStorage.getItem('jwt_key'); 

    console.log('Bearer ' + this.token); 

    this.headers = new Headers({Authorization :'Bearer ' + this.token }); 
    this.headers.set('Content-Type', 'multipart/form-data'); 

    let input = new FormData(); 
    input.append('file', fileToUpload); 

    return this.api 
     .postFile('/profile/upload', input, this.headers).subscribe(
      res => console.log(res.detailedResult), 
      err => console.log(err) 

Aber Haltung von Chrome-Browser immer Fehler, dass: error":"Unauthorized","message":"Full authentication is required to access this resource. Wie kann ich eine Datei in eine URL hochladen, für die eine Authentifizierung erforderlich ist?

+0

Kommt die Fehlermeldung von Chrome oder ist es die Antwort auf die HTTP-Anfrage? – joh04667

+0

Es ist eine Antwort von http, es trifft meinen Haltepunkt, als ich die Authentifizierung von meinem Backend entfernte. – Kenadet

+0

In diesem Fall klingt es wie ein Problem mit Ihrem Back-End. – joh04667

Antwort

-1

Das funktionierte:

headers: Headers; 

token = ''; 


@ViewChild('fileInput') fileInput: ElementRef; 
@ViewChild('profilePic') profilePic:ElementRef; 

constructor(private element: ElementRef, private api: ApiService) {} 

upload(fileToUpload:File) { 

this.token = window.localStorage.getItem('jwt_key'); 

this.headers = new Headers(); 

this.headers.set('Content-Type', 'multipart/form-data'); 

this.headers.append('Authorization', 'Bearer ' + this.token); 

this.api.removeHeader('Content_Type'); 

this.api.setHeaders(this.headers); 

let input = new FormData(); 

return this.api.post ('/profile/upload', input).subscribe(
     res => console.log(res.detailedResult), 
     err => console.log(err) 
    ); 

I Authorization angehängt und entfernt die vorherige Content-type.