x-www-form-urlencoded 跟 multipart/form-data 是兩種能夠傳送formData的MIME 類型
但最近使用Postman打API 卻發現兩者傳參數的方式似乎不相容
ContentType: application/x-www-form-urlencoded (一般請求默認方式)
x-www-form-urlencoded傳送方式是將整個formdata的html form資料當作一個類似query string的方式送出
使用方式上有點像GetMethod (但不同的是,這邊會將請求的整包資料放在message body,而非在url中)
ContentType: application/multipart/form-data
請求標頭內容如下
Content-Type 裡指出使用 multipart/form-data 類型
資料會被分割成數個區塊
然後後方的 boundary 則是說明這是用來標示切割參數的字串
一開始自己在看的時候覺得有點複雜
在看請求內容的分割資料時
可以這麼理解 => 分割符號= 開頭兩個 hypen(--)加上boundary的分割字串
而分割符號跟分割符號間則是表示各個傳入參數或資料的內容
而在請求的最後
一樣也以分割符號再加兩個 hypen(--)標示結束
簡單來說就是把整串紫色字串當作參數區塊間分割字符的概念,
關於boundary的幾個規則
- 開頭是兩個 hypen ( -- )
- 總長度在 70 以內(不包含 hypen 本身)
- 只接受 ASCII 7bit
至於Content-Disposition 的作用在於描述這個資料的格式
每一個參數區塊還可以有各自不同的Content-Type
POST /api/Example HTTP/1.1
Host: 192.168.XX.XXXR
Content-Length: XXX
Content-Type: multipart/form-data; boundary="IamSeparator"
--IamSeparator
Content-Disposition: form-data; name="page"
--IamSeparator
Content-Disposition: form-data; name="id"
999999
--IamSeparatorContent-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain 123321
--IamSeparator--
參考文章
https://newbedev.com/application-x-www-form-urlencoded-or-multipart-form-data
https://dev.to/getd/x-www-form-urlencoded-or-form-data-explained-in-2-mins-5hk6
https://blog.kalan.dev/2021-03-13-html-form-data/
https://www.gushiciku.cn/pl/pK4N/zh-tw
https://javarevisited.blogspot.com/2017/06/difference-between-applicationx-www-form-urlencoded-vs-multipart-form-data.html#ixzz7Avm0RgZd
https://www.microfocus.com/documentation/idol/IDOL_12_0/MediaServer/Guides/html/English/Content/Shared_Admin/_ADM_POST_requests.htm