the request doesn't contain a multipart/form-data or multipart/form-data stream, content type header
一,HTTP上傳的基本知識
在Form元素的語法中,EncType表明提交數據的格式 用 Enctype 屬性指定將數據回發到服務器時瀏覽器使用的編碼類型。下邊是說明: application/x-www-form-urlencoded: 窗體數據被編碼為名稱/值對。這是標准的編碼格式。 multipart/form-data: 窗體數據被編碼為一條消息,頁上的每個控件對應消息中的一個部分。 text/plain:窗體數據以純文本形式進行編碼,其中不含任何控件或格式字符。
補充
form的enctype屬性為編碼方式,常用有兩種:application/x-www-form-urlencoded和multipart/form-data,默認為application /x-www-form-urlencoded。
當action為get時候,瀏覽器用x-www-form-urlencoded的編碼方式把form數據轉換成一個字串(name1=value1& amp; amp;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)。
二,使用中需要注意的地方
在AJAX往服務器上傳數據是,設置了content-type為application/x-www-form-urlencoded,此時是對整個發 送內容作了編碼,並不是對名字對應的值做了編碼。因此,在服務器端,通過request.getParameter("name")的方式取值,是有問題 的。
有兩種解法辦法:
1)改服務器端: 采用流的方式硬編碼
InputStream stream = request.getInputStream(); InputStreamReader isr = new InputStreamReader(stream); BufferedReader br = new BufferedReader(isr); String str = br.readLine(); System.out.println(str); str = URLDecoder.decode(str, "gb2312"); System.out.println(str); br.close();
2)改客戶端:更改數據發送結構
在往服務器上發數據的時候,使用name=escape(value)的方式組對
此時在服務器代碼中,通過request.getParameter("name")獲得的數值,就不用編碼了
當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--