问错了问题,请参阅下面的更新
我需要将我的 AngularJS 项目与现有的 RESTful API 集成。这些 API 使用 POST 请求upload a file
,并在请求中提交表单数据。不幸的是,其中一个表单输入需要位于Content-Type: Application/json
.
在网上搜索后只能POST
with Content-Type: multipart/form-data
其中每个部分没有特定的MIME
。
我怎样才能组成我的multipart/form-data
与不同的MIME
Javascript 中的每个部分?
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--
相关参考文献:
- https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
- REST - 使用 JSON 的 HTTP Post 多部分
- http://code.activestate.com/recipes/578846-composition-a-postable-http-request-with-multipartfo/
- application/x-www-form-urlencoded 还是 multipart/form-data?
- https://stackoverflow.com/a/9082243/764592
Update
为问了错误的问题而道歉。最初的问题是,我可以看到服务器调用类似的逻辑,
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
我还设法弄清楚如何提交这样的帖子请求。我将在下面发布我的答案。
再次抱歉问错问题了。
根据文档FormData,您可以使用以下方法附加具有特定内容类型的字段Blob构造函数:
var formData = new FormData();
formData.append('items', new Blob([JSON.stringify({
name: "Book",
quantity: "12"
})], {
type: "application/json"
}));
仔细观察发现,它会发送如下部分:
Content-Disposition: form-data; name="items"; filename="blob"
Content-Type: text/json
避免自己构建整个请求的唯一选择是传递一个字符串值:
formData.append('items', '{"name": "Book", "quantity": "12"}');
不幸的是,这并没有设置Content-Type
header.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)