JSP upload file

Source: Internet
Author: User
Tags html form

Client

HTML Form forms:

The meaning of enctype= "Multipart/form-data" in the form is to set the MIME encoding of the form. By default, this encoding format is application/x-www-form-urlencoded, cannot be used for file upload, only use the Multipart/form-data to complete the transfer of file data, do the following.

HTML code

<form name="MyForm" action="myjsp.jsp " method="POST"

Enctype="Multipart/form-data">

File1:<br>

<input type="file" name="myfile"><br>

File2:<br>

<input type="file" name="myfile"><br>

<br>

<input type="Submit " Name="Submit " value="Commit" >

</form>

Server-side

Apache Commons-fileupload.jar can facilitate the implementation of File upload function, this example by importing this commons-fileupload.jar. Place Apache Commons-fileupload.jar under the web-inf\lib of the application.

FileUpload is based on Commons io, so make sure the Commons io jar is under web-inf\lib before entering the project.

The main uses are as follows:

Fileitem-------diskfileitemfactory-----servletfileupload

Role:

Fileitem is used to encapsulate elements and data in a form.

Servletfileupload processes the form data and encapsulates the data into the Fileitem object.

Diskfileitemfactory the factory of the Fileitem object, you can set the buffer size and store the temporary file directory.

Servletfileupload handles the data of the uploaded file, takes precedence in the buffer, and if the data exceeds the buffer size, it is saved to the hard disk and stored in a temporary file in the diskfileitemfactory specified directory. After the data is received, it writes the data from the temporary file to the specified file in the upload file directory and deletes the temporary file.

Function:

Limit the size of uploaded files

Long maxsize=1024*1024*3; The unit is byte, so this is the 3M specified here.

Upload.setfilesizemax (MAXSIZE);

Set TEMP directory

Diskfileitemfactory factory = new Diskfileitemfactory ();

Factory.setsizethreshold (1024*1024); Set the buffer of 1M

Factory.setrepository (New File ("E:/temp")); Set up a temporary directory to upload files

If the uploaded file is less than 1M, then the file is in the buffer and then written to the hard disk without passing through the buffer. This will not use the hard disk read and write, should be relatively fast.

Defines the types of files that the server can accept.

string[] Allowtypes = new string[]{"JPG", "jpeg"};

Use the array to define the suffix name of the acceptable file, after reading the contents of the form, get the full name of the client upload file, then intercept the suffix name, take the last one. The subscript, and then get all the strings:

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

An array traversal is not accepted if it is not defined in the array.

throw new RuntimeException ("File type [" +endname+ "], not supported");

The most basic code implementations:
Diskfileitemfactory factory = new Diskfileitemfactory ();
Servletfileupload upload = new Servletfileupload (factory);
try {
list<fileitem> items = upload.parserequest (request); Resolving request Requests
Iterator iter = Items.iterator ();
while (Iter.hasnext ()) {
Fileitem item = (Fileitem) iter.next ();
if (Item.isformfield ()) {//If the form field is a non-file upload element
String name = Item.getfieldname (); Gets the value of the Name property
String value = item.getstring (); Gets the value of the Value property
} else {
String fieldName = Item.getfieldname (); The value of the Name property in the File field
String fileName = Item.getname (); Full path of the file, absolute path name plus file name
String ContentType = Item.getcontenttype (); Types of files
Long size = Item.getsize (); The size of the file, in bytes
File SaveFile = new file ("D:/test.jpg"); Define a file to point to a specific document
Item.write (SaveFile); Write the contents of the upload to a file
}

myjsp.jsp Code

File Uploadpath = new file ("D:\\temp");//Upload Directory

if (!uploadpath.exists ()) {

Uploadpath.mkdirs ();

}

String uploadpath= "D:\\temp";

boolean Ismultipart = servletfileupload.ismultipartcontent (request);

if (Ismultipart = = true) {

Try {

Fileitemfactory factory = newdiskfileitemfactory ();

Servletfileupload upload = newservletfileupload (factory);

list<fileitem> items = upload.parserequest (request);//Get all the files

iterator<fileitem> ITR = Items.iterator ();

while (Itr.hasnext ()) {//process each file sequentially

Fileitem item = (Fileitem) itr.next ();

String filename = item.getname ();//Gets the file name, including the path

if (FileName = null) {

File FullFile = newfile (Item.getname ());

File Savedfile = newfile (Uploadpath,

Fullfile.getname ());

Item.write (Savedfile);

}

}

Out.print ("Upload succeed");

}catch(Exception e) {

E.printstacktrace ();

}

}Else{

Out.println ("The enctype must be Multipart/form-data");

}

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.