问题提出得不正确,请看下面的更新
我需要将我的AngularJS项目与现有的RESTful API集成。这些API会消费POST请求,其中一个请求既上传文件又提交表单数据。但是,其中一个表单输入需要在请求中为Content-Type: Application/json
。
在网上搜索后,我只能使用Content-Type: multipart/form-data
进行POST
,其中每个部分都没有特定的MIME
类型。那么,如何在Javascript中为每个部分组合具有不同MIME
的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--
相关参考文献:
- https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
- REST - HTTP Post Multipart with JSON
- http://code.activestate.com/recipes/578846-composing-a-postable-http-request-with-multipartfo/
- application/x-www-form-urlencoded或multipart/form-data?
- https://dev59.com/e2ox5IYBdhLWcg3wnlpI#9082243
更新
抱歉提出错误的问题。原始问题是我可以看到服务器调用逻辑类似于:
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
我也成功地找出了如何提交这样的帖子请求。我将在下面发布我的答案。再次抱歉问错问题。