Java File upload download

Source: Internet
Author: User

1. Uploading of files
[1] Introduction
> sends a local file of a client to the server for saving.
> Uploading a file sends the file to the server in the form of a stream.

[2] setting of the form
> When uploading a file to the server, the form uses a POST request.
> Default properties for Forms Enctype= "application/x-www-form-urlencoded"
-This attribute means that the content in the request body will be encoded using the URL
> Upload file Form enctype needs to be set to Multipart/form-data
-Multipart/form-data represents a form with multiple parts
-If the type is set to it, then each of our form items will be sent to the server as a separate part.
-Multiple parts are separated using a similar-----------------------------7df2d08c0892 delimiter
> When the form is set to Multipart/form-data, we request.getparameter () will fail, and we can no longer get the request parameters by this method.

[3] FileUpload
> We typically use the Commons-fileupload-1.3.1.jar tool to parse multi-part requests.
> FileUpload relies on Commons-io so if we filtupload need to import IO packages at the same time.
> Core class:
Diskfileitemfactory
-factory class for building a parser instance.

Servletfileupload
-The parser class, which resolves the request information in the requests through the class instance.

Fileitem
-the tool will encapsulate each part of our request as a Fileitem object, only the method that calls the object when processing the file upload
Method
Booleanisformfield ()--whether the current form item is a normal form item, True is a normal form item, FALSE is a file table item
Stringgetcontenttype ()--Returns the type of file, which is a MIME value
Stringgetfieldname ()-Gets the Name property value of the form item
Stringgetname ()-Get the name of the uploaded file
Long GetSize ()-Get the file size
Stringgetstring (String encoding)--Gets the value of the form item, which needs to accept an encoding as a parameter.
Voidwrite (file file)--Writes the contents of a form item to disk

> Use steps:
1. Obtaining a factory class instance [Diskfileitemfactory]
2. Get the parser class instance [Servletfileupload]
3. Parse request get Fileitem[parserequest ()]

Diskfileitemfactory fileitemfactory=new diskfileitemfactory (); Servletfileupload servletfileupload=new servletfileupload (fileitemfactory); try {list<fileitem>fileitems=servletfileupload.parserequest (request); for (Fileitem Fileitem:fileitems) {if ( Fileitem.isformfield ()) {string fieldName = Fileitem.getfieldname ();//The name of the form name string string = Fileitem.getstring (" Utf-8 ");//The property value of the form value long size = Fileitem.getsize (); System.out.println (2+fieldname+3+size+4+string);} else {string name = Fileitem.getname ();//property name string fieldName = Fileitem.getfieldname ();//filename String contentType = Fileitem.getcontenttype ();//file type Long size = Fileitem.getsize ();//File size//filter path in file name if (fieldname.contains ("\ \")) { Fieldname=fieldname.substring (fieldname.lastindexof ("\ \") +1); Fileitem.setfieldname (fieldName);} The set file uniquely identifies the name string uuid = Uuid.randomuuid (). toString (); Fileitem.setfieldname (UUID); try {fileitem.write ("C : \\Users\\Administrator\\Desktop\\ "+uuid+". jpg "));} catch (Exception e) {//TODO auto-generated catchBlocke.printstacktrace ();} System.out.println (1+name+2+fieldname+3+size+4+contenttype);}}} catch (Fileuploadexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}

  


[4] Details
The first one.
> Some browsers send the full path of the file as a filename.
C:\Users\lilichao\Desktop\day20\ pictures \ Mona Lisa. jpg
> Like this kind of file name we need to intercept the string, just get the name part, without having to get the information in the path section.
Use the following code to intercept a string on a file name:
if (name.contains ("\ \")) {
If included, intercepts the string
Name = Name.substring (name.lastindexof ("\ \") +1);
}

A second question
> uploaded files may have duplicate names, the uploaded files will be uploaded before the file is overwritten.
> Workaround: Add a unique prefix to the file name.
Uniquely identifies _fennu.jpg
Uuid_fennu.jpg

A third question
> There are situations where you need to limit the size of uploaded files.
-Set a single file size of 50KB:
Fileupload.setfilesizemax (1024*50);
-Once a single file size limit is set, the following exception is thrown when the uploaded file exceeds the limit:
Filesizelimitexceededexception
All of the exceptions can be captured and an error message is set when the exception occurs.

-Set the total size of multiple files to 150KB
Fileupload.setsizemax (1024*150);
-The following exception is thrown when the size of multiple files is out of range
Sizelimitexceededexception

Question Fourth
> When the user uploads an empty file, the file will still be saved to the hard disk.
> The file size should be judged before saving it, and if size is 0, it will not be processed.

2. Downloading of files
[1] Introduction
> Download the files from the server to local.
> In general, the link to the resource is sent to the browser and the browser is downloaded automatically.
However, when the browser supports the format of the current file, the browser will automatically open the file without ejecting the download window.
> directly puts resources in the project directory, the browser can directly access the resources.
So generally the resources we download cannot be accessed directly by the browser.

[2] What you need to download
1. Get the stream to the file
2. Set two response headers

[3] Download the relevant two response headers
1) file type Content-type--file MIME type
Content-type: Tells the browser file type, need to set a MIME value
Response.setcontent-type ("MIME value")
The MIME type of the file can be obtained directly through the Servletcontext.getmimetype (path) method

2) Download file information content-disposition-attachment; Filename= file name
Content-disposition tells the browser how to process the file,
Attachment tells the browser that this file is a form of attachment to you and requires you to do the download operation
FileName tells the browser to download the file name

3) garbled problem, when the name of the file is set to Chinese, the browser normally displays the name of the file.
Because Chinese is sent from the server to the browser, the content needs to be URL-encoded.
> Most browsers use the following method to solve garbled problems: Urlencoder.encode (FileName, "utf-8");
> But Firefox is decoded by default in Base64, so it should be handled separately for Firefox.

> can use the following code to determine the type of browser, and then do different encoding processing
Determine if the current browser is Firefox
if (Ua.contains ("Firefox")) {
Is the Firefox browser, using BASE64 encoding
FileName = "=?utf-8?b?" +new Base64encoder (). Encode (Filename.getbytes ("Utf-8")) + "? =";
}else{
URL encoding a file name
Urlencoder.encode () requires two arguments, the first argument is the string to encode, and the second is the character set used by the encoding
filename = urlencoder.encode (filename, "utf-8");
}

> There is a less reasonable way, who asks who is anxious. Well, anyway.
-to decode the string with GBK and then encode it using iso8859-1
FileName = new String (filename.getbytes ("GBK"), "iso8859-1");

Java File upload download

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.