phiysng/blog

HTTP Form

phiysng opened this issue · 0 comments

Form可以使用3种编码方式,通过enctype指定。

  • application/x-www-form-urlencoded 使用url encoding 是默认的编码方式,我们一般遇到的都是这种形
  • multipart/form-data 表示一个Multipart form 可以用来上传文件
  • text/plain HTML5新增的编码方式,不使用任何编码

URL Encoded Form

对于如下的Form

<form action="/urlencoded?firstname=sid&lastname=sloth" method="POST" enctype="application/x-www-form-urlencoded">
    <input type="text" name="username" value="sidthesloth"/>
    <input type="text" name="password" value="slothsecret"/>
    <input type="submit" value="Submit" />
</form>

其发送的HTTP请求的负载如下所示,与HTTP的URL编码方式相同。

 username=sidthesloth&password=slothsecret

这种发出去的HTTP请求的头会有如下的属性
Content-Type : application/x-www-form-urlencoded

遇到空格等特殊的字符,这种编码方式会对这些字符进行转义,详见https://stackoverflow.com/questions/2678551/when-to-encode-space-to-plus-or-20。

Multipart Forms

典型的Multipart Forms 如下所示

<form action="/multipart?firstname=sid slayer&lastname=sloth" method="POST" enctype="multipart/form-data">
    <input type="text" name="username" value="sid the sloth"/>
    <input type="text" name="password" value="slothsecret"/>
    <input type="submit" value="Submit" />
</form>

HTTP请求头的类型为Content-Type : multipart/form-data,
另外需要注意的是boundary属性,这个属性用于标识负载中的MIME数据的分界点,类似于URL Encoding中的 & 的作用。

--<<boundary_value>>
Content-Disposition: form-data; name="<<field_name>>"

<<field_value>>
--<<boundary_value>>
Content-Disposition: form-data; name="<<field_name>>"

<<field_value>>
--<<boundary_value>>--

Text/plain Forms

纯文本形式的Forms很少使用,在标准中加入这个属性的目的是让HTTP的负载可以直接被用户,而非机器阅读。

ref : https://dev.to/sidthesloth92/understanding-html-form-encoding-url-encoded-and-multipart-forms-3lpa