通常情況下無(wú)須設(shè)置表單元素的enctype屬性,表單的enctype屬性指定的是表單數(shù)據(jù)的編碼方式,該屬性有如下3個(gè)值:
◆ application/x-www-form-urlencoded:這是默認(rèn)的編碼方式,它只處理表單域里的value屬性值,采用這種編碼方式的表單會(huì)將表單域的值處理成URL編碼方式
◆ multipart/form-data:這種編碼方式會(huì)以二進(jìn)制的方式來(lái)處理表單數(shù)據(jù),這種編碼方式會(huì)把文件域指定文件的內(nèi)容也封裝到請(qǐng)求參數(shù)里
◆ text/plain:這種編碼方式當(dāng)表單的action屬性為mailto:URL的形式時(shí)比較方便,這種方式主要適用于直接通過(guò)表單發(fā)送郵件的方式
下面來(lái)看看enctype屬性為application/x-www-form-urlencoded和multipart/form-data時(shí)的差別
<html> <head> <title>enctype屬性測(cè)試</title> </head> <body> <form action="pro.jsp" method="post" enctype="application/x-www-form-urlencoded"> 上傳文件: <input type="file" name="file" /><br /> 請(qǐng)求參數(shù): <input type="text" name="info" /><br /> <input type="submit" value="提交" /> </form> </body> </html> |
UpdateArticle
注意:application/x-www-form-urlencoded是enctype屬性的默認(rèn)值
提交到的pro.jsp代碼如下:
<%@ page contentType="text/html; charset=GBK"%> <%@ page import="java.io.*"%> <% //獲取HTTP請(qǐng)求的輸入流 InputStream is=request.getInputStream(); //創(chuàng)建緩沖讀入流 BufferedReader br=new BufferedReader(new InputStreamReader(is)); //讀取HTTP請(qǐng)求內(nèi)容 String buffer=br.readLine(); while(buffer!=null){ out.println(buffer); buffer=br.readLine(); } %> |
以上代碼通過(guò)二進(jìn)制流來(lái)處理HTTP請(qǐng)求——這是一種更底層的處理方式,當(dāng)通過(guò)HttpServletRequest的getParameter方法來(lái)獲取請(qǐng)求參數(shù)時(shí),實(shí)際上是Web服務(wù)器替我們處理了這種底層的二進(jìn)制流,并將二進(jìn)制流轉(zhuǎn)換成對(duì)應(yīng)的請(qǐng)求參數(shù)值。
請(qǐng)求數(shù)據(jù)中的文字轉(zhuǎn)碼
public class TestURLEncoder { public static void main(String[] args)throws Exception { String encodeStr="%D0%EC%D6%DD"; System.out.println(URLDecoder.decode(encodeStr,"GBK")); String rawStr="北大青鳥(niǎo)"; System.out.println(URLEncoder.encode(rawStr,"GBK")); } } |
一般情況下,程序中直接通過(guò)HttpServletRequest的getParameter方法即可獲得正確的請(qǐng)求參數(shù),而那些底層的二進(jìn)制流處理,以及使用URLDecoder處理請(qǐng)求參數(shù),都由Web服務(wù)器來(lái)替我們完成了。
但是做文件上串操作的話,僅僅只能獲得文件選擇器中數(shù)值,而不能獲得文件的內(nèi)容,為了實(shí)現(xiàn)文件上傳,必須設(shè)置enctype屬性值為:multipart/form-data