Angular8 http客户端表单数据上传

hei*_*erg 3 multipartform-data angular angular-httpclient

我正在尝试使用 http 客户端上传文件,但我总是从后端得到不好的响应。我假设问题出在请求上,因为除此之外,我的请求所具有的一切都与我在 aurelia http 客户端上发出的请求完全相同。

一般来说,这里有一些关于 angular 请求标头的信息:

Request URL: https://*/document/document?name=ecv_template_en.pdf&classification=0
Request Method: POST
Content-Type: application/json
Request payload:
------WebKitFormBoundary1gYAP6XB8f1TQ7RP
Content-Disposition: form-data; name="blobFile"; filename="ecv_template_en.pdf"
Content-Type: application/pdf
------WebKitFormBoundary1gYAP6XB8f1TQ7RP--
Run Code Online (Sandbox Code Playgroud)

来自 aurelia http 客户端的相同请求:

Request URL: https://*/document/document?name=ecv_template_en.pdf&classification=0
Request Method: POST
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarydb5u93415NsBfKEz
Run Code Online (Sandbox Code Playgroud)

现在没有请求有效负载,而是带有 blobFile: (binary)

这是我为了重现调用而执行的角度代码:

const formData = new FormData();
formData.append("blobFile", documentUpload.file);
return this.http
    .post(`${*}/document?name=${name}&classification=${classification}`, 
     formData).pipe(
        map(do stuff))
    );
Run Code Online (Sandbox Code Playgroud)

我还检查了 formData 的内容,它在 aurelia 请求和角度请求上完全相同。

奥瑞莉亚请求

有角的

我正在调用的端点如下:

    [HttpPost()]
    public ActionResult Create([FromForm]IFormFile blobFile,
        [FromQuery] string name,
        [FromQuery] ClassificationType classification)
Run Code Online (Sandbox Code Playgroud)

hei*_*erg 5

好的,我找到了解决方案。

以前我的 JWT 拦截器有一个定义为 Content-Type: "application/json" 的内容类型,它总是覆盖我的多部分设置器。我已经删除了它,但它没有解决,我开始收到:缺少内容类型边界。

然后我试图删除这个

const httpOptions = {
  headers: new HttpHeaders({
   "Content-Type": "multipart/form-data" // 
  })
};
Run Code Online (Sandbox Code Playgroud)

从请求开始,它起作用了。似乎我不能明确地说出内容类型,否则我会从 .NET Api 获得这种类型的消息。我让浏览器像以前一样处理它。