HTML中的form表單有一個關鍵屬性 enctype

來源:互聯網
上載者:User

標籤:style   http   使用   os   io   資料   for   art   

HTML中的form表單有一個關鍵屬性 enctype=application/x-www-form-urlencoded 或multipart/form-data。

 

1、enctype="application/x-www-form-urlencoded"是預設的編碼方式,當以這種方式提交資料時,HTTP報文中的內容是:

 

Html代碼  
  1. <span style="font-size: small;">POST /post_test.php HTTP/1.1   
  2. Accept-Language: zh-CN  
  3. User-Agent: Mozilla/4.0   
  4. Content-Type: application/x-www-form-urlencoded   
  5. Host: 192.168.12.102  
  6. Content-Length: 42  
  7. Connection: Keep-Alive  
  8. Cache-Control: no-cache  
  9.    
  10. title=test&content=%B3%AC%BC%B6%C5%AE%C9%FA&submit=post+article   
  11. </span>  

Servlet的API提供了對這種編碼方式解碼的支援,只需要調用ServletRequest 類中的getParameter()方法就可以得到表單中提交的資料。


2、在傳輸大資料量的位元據時,必須將編碼方式設定成enctype="multipart/form-data",當以這種方式提交資料時,HTTP報文中的內容是:

 

Html代碼  
  1. <span style="font-size: small;">POST /post_test.php?t=1 HTTP/1.1  
  2. Accept-Language: zh-CN  
  3. User-Agent: Mozilla/4.0    
  4. Content-Type: multipart/form-data; boundary=---------------------------7dbf514701e8  
  5. Accept-Encoding: gzip, deflate  
  6. Host: 192.168.12.102  
  7. Content-Length: 345  
  8. Connection: Keep-Alive  
  9. Cache-Control: no-cache  
  10.    
  11. -----------------------------7dbf514701e8  
  12. Content-Disposition: form-data; name="title"  
  13. test  
  14. -----------------------------7dbf514701e8  
  15. Content-Disposition: form-data; name="content"  
  16. ....  
  17. -----------------------------7dbf514701e8  
  18. Content-Disposition: form-data; name="submit"  
  19. post article  
  20. -----------------------------7dbf514701e8--</span>  

如果以這種方式提交資料就要用request.getInputStream()或request.getReader()來擷取提交的資料 ,用 request.getParameter()是擷取不到提交的資料的。

 

 

最後注意request.getParameter()、request.getInputStream()、request.getReader()這三種方法是有衝突的,因為流只能被讀一次。
比如:
當form表單內容採用enctype=application/x-www-form-urlencoded編碼時,先通過調用request.getParameter()方法擷取資料後,再調用request.getInputStream()或request.getReader()已經擷取不到流中的內容了,因為在調用 request.getParameter()時系統可能對錶單中提交的資料以流的形式讀了一次,反之亦然。

 

當form表單內容採用enctype=multipart/form-data編碼時,調用request.getParameter()擷取不到資料,即使已經調用了request.getParameter()方法也可以再通過調用request.getInputStream()或request.getReader()擷取表單中的資料,但request.getInputStream()和request.getReader()在同一個響應中是不能混合使用的,如果混合使用會拋異常的。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.