In J2EE development, uploading files using a browser is as simple as using Apache’s Commons FileUpload implementation in the server. But you need to deal with it yourself when developing C/S architecture programs. Implementing file uploads in code requires some knowledge of the form’s multipart/form-data.

Forms by default use Application/X-www-form-urlencoded, and in multipart/form-data content-type is coded like this:

Content-Type: multipart/form-data; boundary=--******
Copy the code

Boundary is a separation and is used to separate multiple files. Format – can be followed by a string of random numbers.

I wrote a Servlet myself that used JSP form submission to print out the flow in the request for formatting analysis.

The JSP source code:

Background reception:

Output print:

Analysis of the

  1. If the submission is a file, the format is as follows
------WebKitFormBoundaryxHKqg3ljAsuAFWBO Content-Disposition: form-data; name="upfile"; Filename ="test.png" content-type: image/ PNG ------WebKitFormBoundaryxHKqg3ljAsuAFWBOCopy the code

Content-type is the file Type, which is determined by the browser itself.

  1. If the submission is a form field, the format is as follows
------WebKitFormBoundaryxHKqg3ljAsuAFWBO Content-Disposition: form-data; Name = "note" -- -- -- -- -- - WebKitFormBoundaryxHKqg3ljAsuAFWBO fields contentCopy the code

The separation of all files or fields

------WebKitFormBoundaryxHKqg3ljAsuAFWBO
Copy the code

At the end of execution, the last separator is added with “–“.

------WebKitFormBoundaryxHKqg3ljAsuAFWBO--
Copy the code

You realize ignore this, at that time, lead to code has been an error: org.apache.com mons. Fileupload. FileUploadException: Processing of multipart/form-data request failed. Stream ended unexpectedly

Once you’ve analyzed the multipart/form-data format, it’s easy to write your own code.

  • Client send

  • Server receiving

Download the source code: s3.engr-z.com/wp/2021/upl…

The utility class can be used for JAVA or Android.

This article was originally written in 2016. The old article has not been migrated since the change of domain name and blog. Considering that there is a certain reference value, special integration included in this site. Old links: wangzhengzhen.com/523.html


All original articles on “Siege Lion · Zheng” unless otherwise noted.

Link to this article: engr-z.com/408.html