目錄
entype屬性值
用POST方法把資料傳給後端前
需要先encode
,這是為了維持資料格式符合標準。form的enctype
屬性就是用來規範encode格式
的,目前有3種值,分別如下
application/x-www-form-urlencoded
enctype的預設值
URL encoded form
the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. Non-alphanumeric characters in both keys and values are percent encoded. this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead)
若form如下
<form action="..." method="POST" enctype="application/x-www-form-urlencoded"> <input type="text" name="name" value="tempura samurai" class="mb-2"> <input type="text" name="job" value="samurai" class="mb-2"> <input type="submit" value="Submit" /> </form>
則encode後body如下
// 資料組之間會有&隔開,電腦讀到&就知道一組資料讀完了 name=tempura+samurai&job=samurai name=tempura%20samurai&job=samurais
multipart/form-data
常用於上傳檔案
- 不同格式的資料可以透過同一個請求發送
檔名的特殊字元會被以percent encoded form轉碼
Within this specification, "percent-encoding" (as defined in [RFC3986]) is offered as a possible way of encoding characters in file names that are otherwise disallowed, including non-ASCII characters, spaces, control characters, and so forth. The encoding is created replacing each non-ASCII or disallowed character with a sequence, where each byte of the UTF-8 encoding of the character is represented by a percent-sign (%) followed by the (case-insensitive) hexadecimal of that byte.
若form如下
<form action="..." method="POST" enctype="multipart/form-data"> <input type="file" name="avatar" class="mb-2"> <input type="text" name="name" value="tempura samurai" class="mb-2"> <input type="text" name="job" value="samurai" class="mb-2"> <input type="submit" value="Submit" /> </form>
則encode後body如下
// 資料組之間會有&隔開,電腦讀到&就知道一組資料讀完了 name=tempura%20samurai&job=samurai
text/plain
不encode
,所以body沒有&,進而導致電腦無法分辨是否讀完一組資料了。不推薦使用
Payloads using the text/plain format are intended to be human readable. They are not reliably interpretable by computer, as the format is ambiguous (for example, there is no way to distinguish a literal newline in a value from the newline at the end of the value).
被廢棄的值
application/json
- UTF-8 encoded form
W3C已經不支援 enctype="application/json"
。若瀏覽器不支援,會自動轉為enctype="application/x-www-form-urlencoded"User agents that implement this specification will transmit JSON data from their forms whenever the form's enctype attribute is set to application/json. During the transition period, user agents that do not support this encoding will fall back to using application/x-www-form-urlencoded.
參考資料
Understanding HTML Form Encoding: URL Encoded and Multipart Forms
Define multipart form data
Understanding HTML Form Encoding: URL Encoded and Multipart Forms
Returning Values from Forms: multipart/form-data
HTML Standard- form- control infrastructure
HTML enctype Attribute
W3C - HTML JSON form submission
Postman - 測試 API 神器 1/2