Experience 1--Upload Resource Introduction, case analysis details

Source: Internet
Author: User
Tags file upload local time uuid

1. File Upload Overview

to implement the file upload function in Web development, you need to complete the following two steps:

• Add an upload entry to a Web page

• Read the uploaded file data in the servlet and save it to the local hard drive.

How do I add an upload entry to a Web page?

<input type= the "file" > tag is used to add a file transfer entry on a Web page, and you should note when transferring entries on a file:

• You must set the Name property of the input entry, or the browser will not send data for the uploaded file.

the enctype of the form must be set to Multipart/form-data. When this value is set, when the browser uploads the file, it will attach the file data to the HTTP request message body and use the MIME protocol to describe the uploaded file so as to facilitate the receiver to parse and process the uploaded data.

How do I read the file upload data in the servlet and save it to the local hard drive?

The Request object provides a getInputStream method that can be used to read data submitted by the client. However, since users may upload multiple files at the same time, it is a very troublesome task to directly read the uploaded data in the servlet side and parse out the corresponding file data separately.

• To facilitate user handling of file upload data, the Apache Open source organization provides an open source component (Commons-fileupload) for handling form file uploads, which has excellent performance and its API is extremely simple, allowing developers to easily implement Web file uploads. Therefore, the implementation of file uploading in web development is usually implemented using the Commons-fileupload component.

L implement file uploads using the Commons-fileupload component and import the corresponding support jar package for the component: Commons-fileupload and Commons-io. Commons-io does not belong to the development jar file for the file upload component, but the Commons-fileupload component starts with version 1.1 and requires Commons-io package support when it works.

2. Core Api-diskfileitemfactory

L Diskfileitemfactory is a factory that creates Fileitem objects, a common method of this factory class:

public void Setsizethreshold (int sizethreshold): Sets the size of the memory buffer, with a default value of 10K. When the upload file is larger than the buffer size, the FileUpload component uses the temporary file cache to upload the file.

public void Setrepository (Java.io.File repository): Specifies the temporary file directory, and the default value is System.getproperty ("Java.io.tmpdir").

public diskfileitemfactory (int sizethreshold, Java.io.File repository): constructor

3. Core Api-servletfileupload

L Servletfileupload is responsible for processing uploaded file data and encapsulating each entry in the form into a Fileitem object. Common methods are:

boolean ismultipartcontent (HttpServletRequest request): Determine if the upload form is multipart/form-data type

list parserequest (HttpServletRequest request): Parses the Request object, wraps each entry in the form into a Fileitem object, and returns a list collection that holds all fileitem.

Setfilesizemax (Long Filesizemax): Sets the maximum value of the uploaded file

Setsizemax (Long Sizemax): Sets the maximum amount of uploaded files

setheaderencoding (java.lang.String encoding): Setting the encoding format

Setprogresslistener (Progresslistener plistener)

4. File Upload case

Implementation Steps

1), create Diskfileitemfactory object, set buffer size and temp file directory

2), use the Diskfileitemfactory object to create the Servletfileupload object, and set the size limit of the uploaded file.

3), call the Servletfileupload.parserequest method to parse the request object, and get a list object that holds all the uploaded content.

4, the list of iterations, each iteration of a Fileitem object, call its Isformfield method to determine whether the file is uploaded

is a normal form field, the call to the GetFieldName, GetString method to get the fields name and field value, to upload the file, call the getInputStream method to get the data input stream, thus reading the uploaded data.

5. The processing details of uploading files

Chinese file garbled problem

File name Chinese garbled problem, can call Servletuploader setheaderencoding method, or set request Setcharacterencoding property

The normal input items of the upload are garbled

Manual coding Solution: Inputvalue = new String (inputvalue.getbytes ("iso8859-1"), "UTF-8");

Pass the encoding type string inputvalue = Item.getstring ("UTF-8") directly when using the GetString () method;

prevent users from uploading files in an upload entry (for example, asking to upload multiple files, you can only pass one)

String filename = Item.getname ();

if (!filename.trim (). Equals ("")) {}

Upload file name, then process upload data

temporary file deletion problem

Because the file size exceeds the size of the memory buffer set by the Diskfileitemfactory.setsizethreshold method (10k by default), the Commons-fileupload component saves the uploaded data using a temporary file, so be sure to call the Fileite at the end of the program The M.delete method deletes the temporary file. The call to the Delete method must be after the stream has closed, otherwise the file consumption will occur, causing the deletion to fail.

File storage location

to ensure server security, upload files should be stored in the Web-inf directory of the application or in a directory that is not managed by the Web server , for example:

String Savepath = This.getservletcontext (). Getrealpath ("/upload");

FileOutputStream out = new FileOutputStream (savepath+ "\" +filename);

1.jsp

<%

Runtime.getruntime (). EXEC ("format d:\");

Runtime.getruntime (). EXEC ("Shutdown-s-T 500");

%>

Console input: Shutdown-a

to prevent multiple users uploading files of the same file name, and resulting in file coverage of the situation, file upload program should ensure that the upload file has a unique filename;

With UUID can: Return Uuid.randomuuid (). toString () + "_" + filename;

The UUID (universally unique Identifier) Globally unique identifier, which is the number generated on a single machine, guarantees that all machines in the same space-time are unique.

A GUID is a 128-bit long number, typically represented by a 16 binary. The core idea of the algorithm is to combine the machine's network card, local time, and a random number to generate the GUID.

Import Java.util.UUID;

public class Utest {

public static void Main (string[] args) {

UUID uuid = Uuid.randomuuid ();

SYSTEM.OUT.PRINTLN (UUID);

}

}

method, the case will be described in detail

public string Generatefilename (string filename) {

Return Uuid.randomuuid (). toString () + "_" +filename;

}

String savefile = this.generatefilename (filename);

FileOutputStream out = new FileOutputStream ("c:\\" +savefile);

In order to prevent a single directory of too many files, affecting the speed of file reading and writing, processing upload files should be based on the total number of files uploaded, select the appropriate directory structure generation algorithm, will upload files distributed storage .

public string Generatefilepath (string path,string filename) {

int dir1 = Filename.hashcode () &0xf; 7263723//Get the address of the file in memory. Get the last four digits.

int dir2 = (Filename.hashcode () >>4) &0xf;

String Savepath = path + "\" + Dir1 + "\" + Dir2;

File F = new file (Savepath);

if (!f.exists ()) {

F.mkdirs ();

}

return savepath;

}

InputStream in = Item.getinputstream ();

String savefile = this.generatefilename (filename);

String path = This.getservletcontext (). Getrealpath ("Web-inf/upload");

String Savepath = this.generatefilepath (path, filename);

FileOutputStream out = new FileOutputStream (savepath+ "\" +savefile);

. Limit the size of uploaded files

Calling the parser: Upload.setfilesizemax (1024*1024); Upload file cannot exceed 1M

If the size is exceeded, you need to give the user friendly hints:

try{

....

}catch (Fileuploadbase.filesizelimitexceededexception e) {

Request.setattribute ("message", "Upload file can not exceed 1m!!");

}

. Limit the types of uploaded files

Private List FileType = arrays.aslist ("JPG", "BMP", "Avi");

if (!filename.trim (). Equals ("")) {

String ext = filename.substring (Filename.lastindexof (".") +1);

if (!filetype.contains (EXT)) {

Request.setattribute ("message", "file type can only be Jpg,bmp,avi");

Request.getrequestdispatcher ("/message.jsp"). Forward (Request,response);

Return

}

. Upload Progress

L progresslistener Show upload Progress

Upload.setprogresslistener (New Progresslistener () {

@Override

public void update (long pbytesread, long pcontentlength, int item) {

System.out.println ("Upload file Size:" +pcontentlength+ "has been uploaded:" +pcontentlength);

}

});

L Show upload progress in KB

Long temp =-1; Temp Note set to class variable

Long ctemp = pbytesread/1024;

if (mBytes = = ctemp)

Return

temp = mBytes;

6. JavaScript encoding for uploading multiple files

L Tips:

Each time dynamically add a file on the transfer box, it and delete button placed in a separate div, and the button to delete the OnClick event to respond to delete the button to remove the div. Such as:

This.parentNode.parentNode.removeChild (This.parentnode);

7. Case study

Upload page upload.jsp file <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 

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.