简体   繁体   English

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

[英]Composing multipart/form-data with a different Content-Type on each parts with Javascript (or Angular)

Wrong question asked, see my update below 提出错误的问题,请参阅下面的更新

I need to integrate my AngularJS Project with an existing RESTful API. 我需要将我的AngularJS项目与现有的RESTful API集成。 These API consume POST request which upload a file , and also submit the form data in a request. 这些API使用upload a file POST请求,并在请求中提交表单数据。 Unfortunately, one of the form input requires to be in Content-Type: Application/json . 不幸的是,其中一个表单输入需要在Content-Type: Application/json

After search on the web, I could only POST with Content-Type: multipart/form-data in which each of the parts does not have a specific MIME . 在网上搜索后,我只能使用Content-Type: multipart/form-data进行POST ,其中每个部分都没有特定的MIME How can I compose my multipart/form-data with a different MIME for each parts in Javascript? 如何使用不同的MIME为Javascript中的每个部分组合我的multipart/form-data

POST /api/v1/inventory
Host: localhost:8000
Origin: http://localhost:9000
Content-Type: multipart/form-data; boundary=------border

------border
Content-Disposition: form-data; name="owner"

john doe
------border
Content-Disposition: form-data; name="image"; filename="mybook.png"
Content-Type: image/png


------border
Content-Disposition: form-data; name="items"
Content-Type: application/json

{"name": "Book", "quantity": "12"}
------border--

Relevant References: 相关参考文献:

  1. https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
  2. REST - HTTP Post Multipart with JSON REST - 带有JSON的HTTP Post Multipart
  3. http://code.activestate.com/recipes/578846-composing-a-postable-http-request-with-multipartfo/ http://code.activestate.com/recipes/578846-composing-a-postable-http-request-with-multipartfo/
  4. application/x-www-form-urlencoded or multipart/form-data? application / x-www-form-urlencoded或multipart / form-data?
  5. https://stackoverflow.com/a/9082243/764592 https://stackoverflow.com/a/9082243/764592

Update 更新

Apologize for asking a wrong question. 为提出错误的问题而道歉。 The original problem is that, I can see the server calling the logic something like, 最初的问题是,我可以看到服务器调用逻辑的东西,

func POST(req):
     owner = req.owner // This is string
     image = req.image // This is file object
     itemQuantity = req.items.quantity // Items is an object with attribute quantity
     itemName = req.items.name // Items is an object with attribute name

I have also managed to figure out how to submit such a post request. 我还设法弄清楚如何提交这样的帖子请求。 I will post my answer below. 我将在下面发布我的答案。

Once again sorry for asking a wrong question. 再次抱歉提出错误的问题。

According to the documentation of FormData , you can append a field with a specific content type by using the Blob constructor: 根据FormData的文档,您可以使用Blob构造函数追加具有特定内容类型的字段:

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

This, unfortunately, doesn't set the Content-Type header. 遗憾的是,这不会设置Content-Type标头。

Mistake #1: I mistakenly assume that the items has to be a json, so that we can call its attribute. 错误#1:我错误地认为项目必须是json,以便我们可以调用它的属性。

Solution: To submit a multipart request that contain a file and an object like format is very simple. 解决方案:提交包含文件和格式对象的多部分请求非常简单。

form = new FormData();
form.append('items[name]', 'Book');
form.append('items[quantity]', 12);
form.append('image', imageFile);
form.append('owner', 'John Doe');

So thus the request header and body will looks something like this 因此请求标头和正文看起来像这样

POST /api/v1/inventory
Host: localhost:8000
Origin: http://localhost:9000
Content-Type: multipart/form-data; boundary=------border

------border
Content-Disposition: form-data; name="owner"

john doe
------border
Content-Disposition: form-data; name="image"; filename="mybook.png"
Content-Type: image/png


------border
Content-Disposition: form-data; name="items[name]"

Book
------border
Content-Disposition: form-data; name="items[quantity]"

12
------border--

Nothing would get this to work, until I set the Content-Type header to undefined. 在将Content-Type标头设置为undefined之前,没有什么能够解决这个问题。 In my case I am posting a file and some json. 在我的情况下,我发布了一个文件和一些json。

public uploadFile(code: string, file):angular.IHttpPromise<any>{
    var data = `{"query":"mutation FIRMSCORECARD_CALCULATE($code:String!){ FirmScorecardMutation{ BatchCalculate(Code:$code) }}","variables":{"code":"${code}"},"operationName":"FIRMSCORECARD_CALCULATE"}`;
    var formData = new FormData();
    formData.append('operations', data);
    formData.append('file', file, file.name);

    let config = {
        headers: {
            'Accept': 'application/json',
            'Content-Type': undefined
        }
    };
    let response = this.$http.post(this.graphqlUrl, formData, config);
    return response;
}

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

相关问题 如何提取通过 multipart/form-data 发送的文件的 Content-Type - How to extract the Content-Type of a file sent via multipart/form-data 如何从multipart / form-data正文请求中删除Content-Type? - How to remove Content-Type from multipart/form-data Body Request? 在XHR中使用multipart / form-data作为Content-Type时获得&#39;400 Bad Request&#39; - Getting '400 Bad Request' when using multipart/form-data as Content-Type in XHR Axios multipart/form-data 出现在后端,没有内容类型 - Axios multipart/form-data comes up in the backend with no content-type axios 发布请求正在发送请求 header 的 Content-Type: multipart/form-data 导致未定义的 req.body - axios post request is sending a request header of Content-Type: multipart/form-data resulting in undefined req.body 角度多部分/表单数据表单发送 - Angular multipart/form-data form sending 在multipart / form-data上载的各个部分设置内容长度标题 - Set content-length header on individual parts of a multipart/form-data upload 请求不包含多部分/表单数据或多部分/混合流,内容类型标头为false - the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is false multipart/form-data 可以用javascript发送吗? - multipart/form-data possible to send with javascript? Javascript XHR发送multipart / form-data - Javascript XHR send multipart/form-data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM