【问题标题】:Angular 2 - Authentication does not work with multipart/formdataAngular 2 - 身份验证不适用于 multipart/formdata
【发布时间】:2017-05-09 20:59:47
【问题描述】:

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

    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。那么如何将文件上传到需要认证的url呢?

【问题讨论】:

  • 错误信息是来自 Chrome,还是对 http 请求的响应?
  • 它是来自 http 的响应,当我从后端删除身份验证时,它会到达我的断点。
  • 在这种情况下,这听起来像是您的后端有问题。
  • 我见过很多用springboot上传文件的解决方案,但是没有看到好的解决方案,有没有解决方案?请。
  • 我建议发布一个针对您的后端代码并适当标记的问题。据我所知,这不是 Angular 或前端的问题。

标签: angular authentication spring-boot authorization


【解决方案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

【讨论】:

    猜你喜欢
    • 2016-08-04
    • 2017-02-24
    • 2016-10-22
    • 2017-10-10
    • 2010-11-05
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多