简体   繁体   English

无法使用 Angular 的 HttpClient 上传图片

[英]Can't upload image using Angular's HttpClient

I am able to upload an image perfectly fine using the native fetch POST:我可以使用本机获取 POST 完美地上传图像:

let formData = new FormData();
        formData.append('file', event.target.files[0]);
        console.log(event.target.files[0]);
        fetch('http://localhost:8080/file/upload', {
            method: 'POST',
            headers:{
                'Authorization': 'Bearer ' + JWT
            },
            body:formData
        }).then(response => console.log(response));

However, when I try this using Angular's HttpClient, the request fails since the 'Content-Type': 'multipart/form-data' is not added.但是,当我使用 Angular 的 HttpClient 尝试此操作时,请求失败,因为未添加 'Content-Type': 'multipart/form-data'。

My Angular code:我的角度代码:

The file where I'm calling the service:我在其中调用服务的文件:

this.fileSaverService.uploadImage(event.target.files[0]).subscribe(
            (data)=>{
                console.log(data);
            },
            (error) => {
                console.log(error);
            }
        );

The fileSaverService:文件保护服务:

  uploadImage(fileToUpload) {
    const endpoint = 'http://localhost:8080/file/upload';
    const formData: FormData = new FormData();
    formData.append('file', fileToUpload);
    return this.api
      .post(endpoint, formData, { headers: {'Content-Type': 'multipart/form-data'} });
}

The this.api: this.api:

  post(endpoint: string, body: any, reqOpts: any = {}) {    
    reqOpts.headers = this.handleHeaders(reqOpts.headers);
    return this.http.post(endpoint, JSON.stringify(body), reqOpts);
  }

If I add the header manually when using HttpClient, I get this header without the boundary:如果我在使用 HttpClient 时手动添加标头,我会得到这个没有边界的标头:

在此处输入图片说明

However the native fetch adds this header automatically with the boundary if I don't specify a header and this works perfectly:但是,如果我不指定标头,则本机提取会自动将此标头与边界一起添加,这非常有效:

具有本机提取的内容类型

What are my options here?我在这里有哪些选择?

There are two problems with the code in your question:您问题中的代码有两个问题:

  1. By setting Content-Type to multipart/form-data yourself , the serialisation of your FormData will not result in the correct header with boundaries being set behind the scenes.通过设置Content-Typemultipart/form-data自己,你的序列化FormData不会导致与边界是幕后一套正确的标题。
  2. In your post function, you have JSON.stringify(body) , which is converting your FormData object into a JSON string.在您的post函数中,您有JSON.stringify(body) ,它将您的FormData对象转换为 JSON 字符串。 After doing this, you're simply attempting to POST a string rather than a complete FormData object.这样做之后,您只是尝试 POST 一个字符串而不是一个完整的 FormData 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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