理解HTML表单编码:application/x-www-form-urlencoded、multipart/form-data、text/plain

早过忘川 提交于 2019-12-04 15:02:16

表单提交内容的编码类型由属性enctype决定。它可以有三个值

  • application/x-www-form-urlencoded: 表示使用URL编码的方式来编码表单。如果没有将enctype属性设置为任何值,那么这就是默认值
  • multipart/form-data: 当用户想上传文件这种二进制等文件或者前面的那个方式不能满足时,使用这种类型的表单
  • text/plain: 文本形式,只发送数据而不进行任何编码时使用。

application/x-www-form-urlencoded

使用 & 来分隔键值对,使用 = 来连接键值对。

<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>

对于上面表单的提交,表单数据部分(Form Date),会得到

username=sidthesloth&password=slothsecret

Query String parameters部分,会得到

firstname=sid&lastname=sloth

下面是上面例子 http 请求头 的截图
在这里插入图片描述
使用这个方法还是会有一些问题,例如我们把 username 的值改写一下, 在中间加上空格

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

此时再看看请求头发送的数据是什么样子
在这里插入图片描述
可以看到此时发送的数据都是被编码过的,如何编码请查看百分比编码,

multipart/form-data

多部分表单通常用于用户需要将文件上传到服务器的上下文中。但是,我们只关注简单的基于文本字段的表单,因为了解它们是如何工作的就足够了。

<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>

让我们继续提交它,看看它如何出现在开发工具中。
在这里插入图片描述
Content-Type当中,除了指定来编码格式,还指定了一个 boundary,可以看到它的用途是用于分割 Request Payload 当中的键值对,所以 Form Data 提交的数据格式应该是下面这样

--分割符(boudary)
Content-Disposition: form-data; name="<<field_name>>"

<<field_value>>
--分割符(boudary)
Content-Disposition: form-data; name="<<field_name>>"

<<field_value>>
--分割符(boudary)--

翻译 原文

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!