且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Javascript(或 Angular)在每个部分上使用不同的 Content-Type 组合 multipart/form-data

更新时间:2021-08-15 07:44:25

根据 FormData,您可以使用 Blob 构造函数:

According to the documentation of FormData, you can append a field with a specific content type by using the Blob constructor:

var formData = new FormData();

formData.append('items', new Blob([JSON.stringify({
    name: "Book",
    quantity: "12"
})], {
    type: "application/json"
}));

仔细观察,原来它会发送部分如下:

After careful observation, it turns out that it will send the part as follows:

Content-Disposition: form-data; name="items"; filename="blob"
Content-Type: text/json

避免自己构建整个请求的唯一替代方法是传递一个字符串值:

The only alternative, safe from building the whole request yourself is to pass a string value:

formData.append('items', '{"name": "Book", "quantity": "12"}');

不幸的是,这不会设置 Content-Type 标头.

This, unfortunately, doesn't set the Content-Type header.