Multipart form-data Boundary

Source: Internet
Author: User
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. The browser of the client, such
Microsoft IE, ILA Ila, opera, etc. According to this specification, user-specified files are sent to the server. Web programs on the server, such as PHP, ASP,
JSP, etc. According to this specification, the file sent by the user can be parsed. Microsoft IE, ILA Ila, opera
This Protocol is already supported. You can use a special form on a webpage to send files. Most HTTP servers, including Tomcat
. This protocol is supported and files can be sent. 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. write a third-party HTTP
There are many Upload File tool libraries. The jarkata project provides fileupload
Pack http://jakarta.apache.org/commons/fileupload.

File Upload, form item processing, efficiency problem Base
This is all taken into account. This package is used in struts, but it is encapsulated separately in struts mode. Here we use fileupload directly
Package. 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

Http: // 192.168.29.65/upload_file/uploadfile. Suppose we want to send a binary file, a text box form entry, a password

Box form items. 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
192.168.29.65 sends the following content:

 

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.
Field Format: fieldname = value. Separate each field. Note that all fields are processed as strings. What we need to do is simulate the browser 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);

 
It should be noted 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 this
For the encode () method, see the source code of java.net. urlencoder. java. The rest is to read the server response. The Code is the same as the get code, so it is not detailed 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 detect POST requests sent by IE, you can find that the IE separator is similar
--------------------------- 7d4a6d158c9, which is a random number generated by IE to prevent the server from being uploaded due to separators in files.
The start position of the file cannot be correctly identified. 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/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/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...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.