1. 程式人生 > >關於ajax 上傳圖片 enctype="multipart/form-data"的問題

關於ajax 上傳圖片 enctype="multipart/form-data"的問題

該屬性為提交表單瀏覽器對資料的編碼方式,常用有兩種:application/x-www-form-urlencoded和multipart/form-data,預設為application/x-www-form-urlencoded。

當action為get時候,瀏覽器用x-www-form-urlencoded的編碼方式把form資料轉換成一個字串(name1=value1&name2=value2...),然後把這個字串append到url後面,用?分割,載入這個新的url。
當action為post時候,瀏覽器把form資料封裝到http body中,然後傳送到server。

如果沒有type=file的控制元件,用預設的application/x-www-form-urlencoded就可以了。
但是如果有type=file的話,就要用到multipart/form-data了。瀏覽器會把整個表單以控制元件為單位分割,併為每個部分加上Content-Disposition(form-data或者file),Content-Type(預設為text/plain),name(控制元件name)等資訊,並加上分割符(boundary)。
如果有以下form,並選擇了file1.txt上傳
<form action="http://server.com/cgi/handle"
enctype="multipart/form-data"
method="post">
<input type="text" name="submit-name" value="chmod777"><br />
What files are you sending? <input type="file" name="files"><br />
</form>

則有如下body:
Content-Type: multipart/form-data; boundary=AaB03x

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

chmod777
--AaB03x
Content-Disposition: form-data; name="files"; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--AaB03x--