1. What is Multipart/form-data
First we need to understand the Enctype property in HTML,
Enctype: Specifies how form forms are encoded when sent to the server. He has the following three values.
- ①application/x-www-form-urlencoded. The default encoding method.
However, the use of this encoding is inefficient in the case of large files such as text transmission and MP3.
- ②multipart/form-data.
Specifies the transfer data as 二进制类型
, MP3, file.
- ③text/plain.
纯文体
The transmission.
Spaces are converted to "+" plus signs, but special characters are not encoded.
2. Specify what the post and get request parameters and the request body form a GET request when the Enctype parameter is application/x-www-form-urlencoded
Request Header:
GET /www.xxx.com?name=%22hello+world%22&**file=temp.png**&submit=submit HTTP/1.1
Because the GET request does not have a request body, all of his parameters are added behind the URL. The Type=file form item can only get the name of the file and cannot get the contents of the file.
POST request
Request Header:
POST /www.baidu.com HTTP/1.1
Request Body:
name=%22hello+world%22&file=temp.png&submit=submit
Summarize
- (1) We can find that both the POST request and the GET request, their parameters exist in the form of a constant, through the form of key=value exist.
- (2) The form item type=filed can only get the name of the obtained file cannot get the contents of the file.
3. Specify what form the post and get request parameters and the request body are when the enctype parameter is Multipart/form-data
GET request
Request Header:
GET/www.xxx.com?name=%22hello+world%22&file=temp.png&submit=submit HTTP/1.1
GET request
The GET request and the Multipart/form-data combination are not valid because the file upload requires the request body.
POST request:
Request Header:
POST /www.xxx.com HTTP/1.1
Request Body:
------WebKitFormBoundaryIZDrYHwuf2VJdpHwContent-Disposition: form-data; name="name""hello world"------WebKitFormBoundaryIZDrYHwuf2VJdpHwContent-Disposition: form-data; name="file"; filename="temp.png"Content-Type: image/png.PNG....IHDR.............Y../..,+|.$aIk.v...G?...P.P,,...m..e.2....v.7. pHYs...%...%.IR$....|IDAT(.cTT....................:.?.......}.(.Pd`A..V...L...?..#.....4.o..LS.....W.d.?...A8..LS...(.u.......D.b......b.....o&..;..<.1......IEND.B`.------WebKitFormBoundaryIZDrYHwuf2VJdpHwContent-Disposition: form-data; name="submit"submit------WebKitFormBoundaryIZDrYHwuf2VJdpHw--
By observing that the request body has changed. This request body is called the multi-part Request body.
What is a multipart request body: Splits each form item into a single part.
Because the form items are divided into normal and file form items, there is a difference between the parts.
Content-Disposition: form-data; name="file"; filename="temp.png"Content-Type: image/png
A request body:
.PNG....IHDR.............Y../..,+|.$aIk.v...G?...P.P,,...m..e.2....v.7. pHYs...%...%.IR$....|IDAT(.cTT....................:.?.......}.(.Pd`A..V...L...?..#.....4.o..LS.....W.d.?...A8..LS...(.u.......D.b......b.....o&..;..<.1......IEND.B`.------WebKitFormBoundaryIZDrYHwuf2VJdpHwContent-Disposition: form-data; name="submit"submit------WebKitFormBoundaryIZDrYHwuf2VJdpHw--
Summary: The parameters are not obtained primarily because the request body has changed after using the Multipart/form-data property. It is not the form of key=value, so it cannot be obtained.
Workaround:
(1) We can use the JS code to make some changes, append our parameters to the URL behind.
<form id="upload" name="upload" action="fileftp.jsp" method="post" ENCTYPE="multipart/form-data"> <input type="hidden" name="otherName" id="otherName" value="abcdefg"/> <td nowrap> <input type="file" id="file1" name="file1" value="" size="40" class="sbttn"/> <input type="submit" value="上传" class="sbttn"/> </td> </form>
<script language="javascript"> function formSubmit(){ var action="fileftp.jsp"; action+="?otherName="+document.upload.otherName.value; document.upload.action=action; document.upload.submit();}</script>
(2) by modifying the server-side code. The premise is to take advantage of the jar package.
Commons-fileupload-1.2.2.jar and Commons-io-1.4.jar
//Create factory diskfileitemfactory factoy=new diskfileitemfactory ();//create Parser Servletfileupload sfu=new Servletfileupload (Factoy);//Parse Requesttry {list<fileitem> list=sfu.parserequest (request); for (Fileitem fileitem:list) {fileitem.getfieldname (); System.out.println (Fileitem.getstring ()); }} catch (Fileuploadexception e) {//TODO auto-generated catch block E.printstacktrace ();}
Package Cn.zll.bookstore.adminbook.servlet;import Java.awt.image;import Java.io.file;import java.io.IOException; Import Java.util.list;import Java.util.uuid;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.swing.imageicon;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.fileuploadbase;import Org.apache.commons.fileupload.fileuploadexception;import org.apache.commons.fileupload.disk.DiskFileItemFactory ; Import Org.apache.commons.fileupload.servlet.servletfileupload;import Cn.zll.bookstore.adminbook.service.service;import Cn.zll.bookstore.book.domain.book;public class UploadServlet Extends HttpServlet {public void DoPost (HttpServletRequest request, httpservletresponse response) throws Se Rvletexception, IOException {service s=new service (); Response.setcontenttype ("Text/html;charset=utf-8");Request.setcharacterencoding ("Utf-8"); File Upload Trilogy//create Factory diskfileitemfactory factoy=new diskfileitemfactory (); Create parser Servletfileupload sfu=new servletfileupload (Factoy); Set the size of the upload file Sfu.setfilesizemax (20*1024); Parse the request try {list<fileitem> list=sfu.parserequest (request); Book B=new book (); B.setbid (Uuid.randomuuid (). toString (). Replace ("-", "" ")); String bname=list.get (0). getString ("Utf-8"); B.setbname (bname); System.out.println (bname); String Price=list.get (2). getString ("Utf-8"); B.setprice (price); String Author=list.get (3). getString ("Utf-8"); B.setauthor (author); String Cid=list.get (4). getString ("Utf-8"); B.setcid (CID); System.out.println (BNAME+PRICE+AUTHOR+CID);//Book Name: <input style= "width:150px; height:20px; "type=" text "name=" bname "/><br/>// Book Picture: <input style= "WIDTH:223PX; height:20px; "type=" file "name=" image "/><br/>//book Price: <input style=" width:150px; height:20px; "type=" text "name=" Price "/><br/>//book <input style=" width:150px; height:20px; "type=" text "name=" author "/><br/>//Book Classification: <select style=" width:150px; height:20px; "Name=" CID ">/////Set Picture saved directory String Path=this.getservletcontext (). g Etrealpath ("/book_img"); Gets the file name String filename=uuid.randomuuid (). toString (). Replace ("-", "") + "_" +list.get (1). GetName (); Verify the format of the picture if (!filename.tolowercase (). EndsWith ("jpg")) {System.out.println ("picture format is not JPG"); Request.setattribute ("msg", "Your picture format is not JPG format"); Request.getrequestdispatcher ("/adminjsps/admin/book/add.jsp"). Forward (request, response); Return }//Use directory and file name to create the target file f=new files (PATh,filename); Save file List.get (1). write (f); Verify the size of the picture image Image=new ImageIcon (F.getabsolutepath ()). GetImage (); if (Image.getwidth (null) >200 | | image.getheight (NULL) >200) {f.delete (); Request.setattribute ("msg", "the size of the picture is too large"); Request.getrequestdispatcher ("/adminjsps/admin/book/add.jsp"). Forward (request, response); }//Set the property of book B.setimage ("book_img/" +filename); S.add (b); Request.setattribute ("MSG", "add success"); Request.getrequestdispatcher ("/adminjsps/admin/book/add.jsp"). Forward (request, response); System.out.println ("FileName:" +filename); SYSTEM.OUT.PRINTLN (path); } catch (Fileuploadexception e) {if (e instanceof fileuploadbase.filesizelimitexceededexception) { System.out.println ("The file you uploaded is larger than 15K"); Request.setattribute ("msg", "Your picture is greater than 15k"); ReQuest.getrequestdispatcher ("/adminjsps/admin/book/add.jsp"). Forward (request, response); Return } e.printstacktrace (); } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); } }}
Multipart/form-data File Upload form The reason why pass parameters cannot be obtained!