Angular 2 - 身份验证不适用于multipart / formdata

时间:2017-05-09 20:59:48

标签: angular authentication spring-boot authorization

我正在尝试使用以下代码上传文件:

    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)

但是不断从Chrome浏览器中获取错误:error":"Unauthorized","message":"Full authentication is required to access this resource。那么如何将文件上传到需要身份验证的网址呢?

1 个答案:

答案 0 :(得分:-1)

这有效:

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

我添加了Authorization,并删除了之前的Content-type