javascript - 无法使用 Angular 的 HttpClient 上传图片

标签 javascript angular http

我可以使用原生获取 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));

但是,当我使用 Angular 的 HttpClient 尝试此操作时,请求失败,因为未添加 'Content-Type': 'multipart/form-data'。

我的 Angular 代码:

我调用服务的文件:

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

文件保存服务:

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

this.api:

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

如果我在使用 HttpClient 时手动添加 header ,我会得到这个没有边界的 header :

enter image description here

但是,如果我没有指定 header ,则 native 提取会自动将此 header 添加到边界,并且效果很好:

Conent type with native fetch

我有哪些选择?

最佳答案

你问题中的代码有两个问题:

  1. 通过将 Content-Type 设置为 multipart/form-data yourselfFormData 的序列化将不会导致在幕后设置边界的正确 header 。
  2. 在您的 post 函数中,您有 JSON.stringify(body),它将您的 FormData 对象转换为 JSON 字符串。执行此操作后,您只是在尝试 POST 字符串而不是完整的 FormData 对象。

关于javascript - 无法使用 Angular 的 HttpClient 上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52059569/

相关文章:

delphi - 什么会导致套接字在每次 HTTP 事务后快速关闭?

java - 根据 HTTP 规范, '*' 是内容类型的有效通配符吗?

javascript - 在 html 标签中添加 html 数据属性的标准方法?

javascript - 如何从ReactJS中的初始页面请求中获取HTTP请求 header

npm - 如何正确地将 angular 2 (npm) 升级到最新版本?

Angular 无法在外部库中使用 HttpClient

javascript - 来自不同域的 Greasemonkey AJAX 请求?

javascript - 无法在javascript中正确更改父元素

javascript - BNG 中的 Open Layers 3 鼠标位置检测不起作用

angular - 在 Ionic 3 中使用全局变量时出错