html form multipart,html – 为什么上传文件时需要form enctype = multipart/form-data?

它与浏览器如何打包二进制数据并通过HTTP传输形成数据有关。默认情况下只发送表单数据,但是如果表单需要支持上传文件,则二进制数据也必须附加并与表单数据分离。

Scott Hanselman给了这个here的很好的解释:

HTTP and How File Upload works via HTTP

It’s always better, for me, to understand WHY and HOW something is happening. If you say “just because” or “whatever, you just add that, and it works” then I think that’s sad. For some reason while many folks understand FORM POSTs and generally how form data is passed up to the server, when a file is transferred many just conclude it’s magic. Why do we have to add enctype=”multipart/form=data” on our forms that include file uploads? Because the form will now be POSTed in multiple parts.

If you have a form like this:

Filename:

The resulting Form POST will look like this (slightly simplified):

POST /home/uploadfiles HTTP/1.1

Content-Type: multipart/form-data; boundary=---------------------------7d81b516112482

Accept-Encoding: gzip, deflate

User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64)

Content-Length: 324

-----------------------------7d81b516112482

Content-Disposition: form-data; name="file"; filename="\\SERVER\Users\Scott\test.txt"

Content-Type: text/plain

foo

-----------------------------7d81b516112482

Content-Disposition: form-data; name="submit"

Submit

-----------------------------7d81b516112482--

Notice a few things about this POST. First, notice the content-type and boundary=”” and how the boundary is used later, as exactly that, a boundary between the multiple parts. See how the first part shows that I uploaded a single file, of type text/plain. You can interpolate from this how you’d expect multiple files to show up if they were all POSTed at once.

And of course, look at how different this would look if it were just a basic form POST without the enctype=”multipart/form=data” included:

POST /home/uploadfiles HTTP/1.1

Content-Type: application/x-www-form-urlencoded

UA-CPU: x86

Accept-Encoding: gzip, deflate

User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64)

Content-Length: 13

submit=Submit

See how the content type is different? This is a regular, typical form POST. Perhaps atypical in that it includes only a Submit button!

….

As an aside, if you looked at an email of yours with multiple attached files, it would look VERY similar to the body of the first HTTP message as multipart MIME encoding is found everywhere, as is common with most good ideas.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值