问题描述
我注意到(至少)有两种通过API将文件上传到HTTP服务器的方式.
您可以使用multipart/form-data
(这是浏览器在本地执行的用于文件上传HTML输入的操作),但是您也可以POST
请求正文中的文件内容(也许具有正确的Content-Type请求标头). /p>
每种方法的优缺点是什么(总的来说,不是来自浏览器)?
例如,多部分请求–根据您在编程环境中使用的http或网络库(我在服务器端使用Node.js,在客户端使用Swift)–创建然后再复杂一些解析.
协议级别的唯一区别是multipart/form-data
请求必须遵守 RFC 2388 ,而自定义类型的请求正文可以是任意的.
由此产生的实际含义是,multipart/form-data
请求通常更大:尽管从技术上允许客户端使用非7位的content-transfer-encoding
,但大多数情况下仍使用base64. MIME头会产生额外的开销,如果上载许多小文件,这些开销可能会成为瓶颈.请注意,在现有客户端/库中对multipart/form-data
文件上载的支持要广泛得多.如果您不确定客户端和中间主机(代理服务器)的功能集,则应始终将其作为备用.尤其要记住,如果您正在为第三方设计API,那么其他开发人员将已经很熟悉multipart/form-data
并准备好使用它的库.
I noticed there are (at least) two ways of uploading a file to a HTTP server via an API.
You can use multipart/form-data
(which is what browsers do natively for file upload HTML inputs), but you can also POST
the file content inside the request body (perhaps with the correct Content-Type request header).
What are the pros and cons of each method (in all generality, not from a browser)?
Multipart requests for instance – depending on which http or networking library you use in your programming environment (I use Node.js on the server side and Swift on the client side) – seem to be a bit more complex to create and then parse.
The only difference on the protocol level is that multipart/form-data
requests must adhere to RFC 2388 while a custom typed request body can be arbitrary.
The practical implication from this is that a multipart/form-data
request is typically larger: While clients are technically allowed to use a non-7bit content-transfer-encoding
, base64 is used by most. The MIME headers generate additional overhead that can become a bottleneck if many small files are uploaded. Note that support for multipart/form-data
file uploads in existing clients/libraries is far more widespread. You should always provide it as a fallback if you are not sufficiently certain about the featureset of your clients and intermediate hosts (proxy servers). Especially keep in mind that if you are designing an API for third parties that other developers will already be familiar with multipart/form-data
and have libraries at hand to work with that.
这篇关于文件上传API:主体中的多部分/表单数据与原始内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!