Original translated from: http://yefeng.iteye.com/blog/315847
Description: enctype = "multipart/form-Data" Description:
Rfc1867 protocol overview, JSP application example, and client-sent content construction
1. Overview In the original HTTP protocol, there was no file upload function. Rfc1867 (http://www.ietf.org/rfc/rfc1867.txt) added this feature for the HTTP protocol. Client browsers, such as Microsoft IE, ILA Ila, and opera, send user-specified files to the server according to this specification. Web programs on the server, such as PHP, ASP, and JSP, can parse the files sent by the user according to this specification. Microsoft IE, ILA Ila, and opera already support this protocol. You can use a special form on the webpage to send files. Vast majority
HTTP server, including tomcat, supports this protocol and can send files. Various web programs, such as PHP, ASP, and JSP, have encapsulated the uploaded files.
2. Example of uploading files: implement with servelet (HTTP server is Tomcat 4.1.24) 1. Write the following form in an HTML webpage:
<Form enctype = "multipart/form-Data" Action = "http: // 192.168.29.65/uploadfile" method = post>
Load multi files: <br>
<Input name = "userfile1" type = "file"> <br>
<Input name = "userfile2" type = "file"> <br>
<Input name = "userfile3" type = "file"> <br> <input name = "userfile4" type = "file"> <br>
Text Field: <input type = "text" name = "text" value = "text"> <br>
<Input type = "Submit" value = "Submit"> <input type = reset> </form>
You can select multiple files and fill in other items in the form. Click "Submit" to upload the files to http: // 192.168.29.65/upload_file/uploadfile.
This is a servelet program. Note that enctype = "multipart/form-Data", method = post, type = "File ". According to rfc1867, these three attributes are required. Multipart/form-data is a new encoding type to improve the transmission efficiency of binary files. For more information, see rfc18672. currently, there are many third-party HTTP Upload File tool libraries. The jarkata project itself provides the fileupload package http://jakarta.apache.org/commons/fileupload/
.
File Upload, form Item Processing, and efficiency are all taken into account. This package is used in struts, but it is encapsulated separately in struts mode. Here we use the fileupload package directly. For the usage of struts, see the struts documentation. The main code of this servelet processing file upload is as follows:
Public void dopost (httpservletrequest request, httpservletresponse response)
{
Diskfileupload = new diskfileupload (); // maximum file length allowed
Diskfileupload. setsizemax (100*1024*1024); // set the memory buffer size
Diskfileupload. setsizethreshold (4096); // you can specify a temporary directory.
Diskfileupload. setrepositorypath ("C:/tmp ");
List fileitems = diskfileupload. parserequest (request );
Iterator iter = fileitems. iterator (); For (; ITER. hasnext ();)
{
Fileitem = (fileitem) ITER. Next ();
If (fileitem. isformfield () {// currently a form item
Out. println ("form field:" + fileitem. getfieldname () + "," + fileitem. getstring ());
} Else {
// Currently an uploaded file
String filename = fileitem. getname ();
Fileitem. Write (new file ("C:/uploads/" + filename ));
}
}}
For the sake of simplicity, details such as exception handling and file rename are not provided. 3. Construct the content sent by the client. Assume that the webpage program that receives the file is located at http: // 192.168.29.65/upload_file/uploadfile. suppose we want to send a binary file, a text box form item, and a password box form item. The file name is E: \ s, and the content is as follows: (xxx represents binary data, for example 01 02 03) The abbxxxccc client should send the following content to 192.168.29.65:
Post/upload_file/uploadfile HTTP/1.1
Accept: text/plain ,*/*
Accept-language: ZH-CN
HOST: 192.168.29.65: 80
Content-Type: multipart/form-data; boundary = --------------------------- 7d33a816d302b6
User-Agent: Mozilla/4.0 (compatible; OpenOffice.org)
Content-Length: 424
Connection: keep-alive ----------------------------- 7d33a816d302b6
Content-Disposition: Form-data;
Name = "userfile1 ";
Filename = "E: \ s" Content-Type:
Application/octet-stream abbxxxccc
----------------------------- 7d33a816d302b6
Content-Disposition: Form-data;
Name = "text1" foo
----------------------------- 7d33a816d302b6
Content-Disposition: Form-data;
Name = "password1" Bar
----------------------------- 7d33a816d302b6 --
(There is a carriage return on it) the content must be a single character, including the last carriage return.
Note: Content-Length: 424 here 424 is the total length of the Red content (including the last carriage return)
Note This line: Content-Type: multipart/form-data; boundary = --------------------------- 7d33a816d302b6
According to rfc1867, multipart/form-data is required. --------------------------- 7d33a816d302b6 is a delimiter that separates multiple files and form items.
33a816d302b6 is a number generated in real time to ensure that the entire separator does not appear in the content of the file or form item. The previous --------------------------- 7D is a unique identifier of IE.
Mozila is ----------------------------- 71. This example is manually sent and passed in the servlet above.
Use post to send data
The post method is mainly used to send a large amount of client data to the server, which is not limited by the URL length. The post request places the data in the HTTP body in URL encoding format. The field format is fieldname = value, and each field is separated. Note that all fields are processed as strings. In fact, what we need to do is simulate the browser to post a form. The following is a POST request sent by IE to a login form:
Post http: // 127.0.0.1/login. Do HTTP/1.0
Accept: image/GIF, image/JPEG, image/pjpeg ,*/*
Accept-language: En-US, ZH-CN; q = 0.5
Content-Type: Application/X-WWW-form-urlencoded
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
Content-Length: 28
\ R \ n
Username = Admin & Password = 1234
To simulate a browser in the MIDP application to send this POST request, first set the HTTP Connection Request Method to post:
HC. setrequestmethod (httpconnection. post );
Then construct the HTTP body:
Byte [] DATA = "username = Admin & Password = 1234". getbytes ();
And calculate the body length, and fill in Content-Type and Content-Length:
HC. setrequestproperty ("Content-Type", "application/X-WWW-form-urlencoded ");
HC. setrequestproperty ("Content-Length", String. valueof (data. Length ));
Enable outputstream to write the body:
Outputstream output = HC. openoutputstream ();
Output. Write (data );
Note that the data still needs to be encoded in URL encoding format. Because the MIDP library does not have the urlencoder class corresponding to j2se, you need to write the encode () method by yourself, for more information, see java.net. urlencoder. java source code. The rest is to read the server response, and the code is consistent with get, so we will not detail it here.
Use multipart/form-data to send files
To upload files to the server on the MIDP client, we must simulate a post multipart/form-data request. The content-type must be multipart/form-data.
The format of post requests encoded with multipart/form-data is completely different from that of application/X-WWW-form-urlencoded. To use multipart/form-data, you must first set a separator in the HTTP request header, for example, ABCD:
HC. setrequestproperty ("Content-Type", "multipart/form-data; boundary = ABCD ");
Then, each field is separated by "-- separator", and the last "-- Separator --" indicates the end. For example, to upload a title field "today" and a file c: \ 1.txt, the HTTP body is as follows:
-- ABCD
Content-Disposition: Form-data; name = "title"
\ R \ n
Today
-- ABCD
Content-Disposition: Form-data; name = "1.txt"; filename =" C: \ 1.txt"
Content-Type: text/plain
\ R \ n
<This is the content of the 1.txt File>
-- ABCD --
\ R \ n
Note that each row must end with \ r \ n, including the last row. If you use the sniffer program to check the POST request sent by IE, you can find that the IE separator is similar to ------------------------- 7d4a6d158c9, which is a random number generated by IE, the purpose is to prevent the server from correctly identifying the start position of a file due to a separator in the uploaded file. We can write a fixed separator as long as it is complex enough.
The post code for sending the file is as follows:
String [] props =... // field name
String [] values =... // Field Value
Byte [] file =... // File Content
String boundary = "--------------------------- 7d4a6d158c9"; // delimiter
Stringbuffer sb = new stringbuffer ();
// Send each field:
For (INT I = 0; I
SB = sb. append ("--");
SB = sb. append (Boundary );
SB = sb. append ("\ r \ n ");
SB = sb. append ("content-Disposition: Form-data; name = \" "+ props [I] +" \ "\ r \ n ");
SB = sb. append (urlencoder. encode (Values [I]);
SB = sb. append ("\ r \ n ");
}
// Send the file:
SB = sb. append ("--");
SB = sb. append (Boundary );
SB = sb. append ("\ r \ n ");
SB = sb. append ("content-Disposition: Form-data; name = \" 1 \ "; filename = \" 1.txt \ "\ r \ n ");
SB = sb. append ("Content-Type: Application/octet-stream \ r \ n ");
Byte [] DATA = sb. tostring (). getbytes ();
Byte [] end_data = ("\ r \ n --" + boundary + "-- \ r \ n"). getbytes ();
// Set the HTTP header:
HC. setrequestproperty ("Content-Type", multipart_form_data + "; boundary =" + boundary );
HC. setrequestproperty ("Content-Length", String. valueof (data. Length + file. Length + end_data.length ));
// Output:
Output = HC. openoutputstream ();
Output. Write (data );
Output. Write (File );
Output. Write (end_data );
// Read the server response:
// Todo...