Upload and download files using JSP

Source: Internet
Author: User

Use Apache's fileupload class library to upload files
I. Web Resources
Fileupload homepage: Http://commons.apache.org/fileupload/
Commons Io Class Library: Http://commons.apache.org/io/ , Fileupload needs to be used for this class library,
Therefore, make sure that the class library is in your classpath. Otherwise, an exception occurs.
Ii. Related Classes and interfaces
1. diskfileitemfactory class
Fileitemfactory is implemented. The file item factory is translated by name. The actual function is to define the memory occupied by files during file transfer and the storage location of temporary files when the memory is occupied, the main method is as follows:
Void setsizethreshold (INT sizethreshold)
// Set the memory usage of the file in bytes and save the file to temporary storage.
Void setrepository (Java. Io. File Repository) // set the storage path of the temporary file
2. servletfileupload class
Classes used to process multi-File Uploads in the same HTML file are inherited from fileupload. The main method is as follows:
Java Code
1. Static Boolean ismultipartcontent (javax. servlet. http. httpservletrequest request)
// Determine whether the client request is post and whether the enctype attribute is "multipart/form-Data"
2. Public java. util. List parserequest (javax. servlet. http. httpservletrequest request)
Throws fileuploadexception // read the "multipart/form-Data" data stream and obtain the list of form items.
3. Void setsizemax (long sizemax) // you can specify the maximum size of the file to be uploaded.
Before obtaining the uploaded file, you must first determine whether the enctype attribute marked by the client <form> is "multipart/form-Data". You can use Org. apache. commons. fileupload. servlet. determine the ismultipartcontent () method in the servletfileupload class
3. fileitem Interface
Name Translation is a file item that represents a control in the submitted form. The parserequest () file in servletfileupload returns a list Of all fileitem items in the form.

1 Boolean isformfield () // determines whether the form item is a file item or a common form item.
2 string getfieldname () // if it is not a file item, return the form name of the corresponding form item.
3 string getstring () // if it is not a file item, the content of the item is returned by default encoding.
4 string getstring (string encoding) // return the content of the item with the specified encoding.
5 long getsize () // return the size of the item in bytes.
6 string getname () // if it is a file entry, this method returns the file name, the file name depends on the client browser
7 void write (Java. Io. File file) // if it is a file item, write the file to the corresponding file
8 java. Io. inputstream getinputstream ()
9 java. Io. outputstream getoutputstream ()
Iii. Usage
1. First, store the fileupload package and its related commons Io package in the WEB-INF/lib of the Web application.
2. For a simple example, run the file and save it to a directory on disk D.
Java code
1 // File Upload example Program
2 // determine whether the form is enctype = "multipart/form-Data"
3 if (servletfileupload. ismultipartcontent (request )){
4
5 diskfileitemfactory dfif = new diskfileitemfactory ();
6 dfif. setsizethreshold (5*1024*1024); // when the memory usage exceeds 5 MB, temporary files are generated and stored in the temporary directory.
7 dfif. setrepository (new file ("C: // Temp"); // you can specify the directory for storing temporary files.
8
9 servletfileupload fileupload = new servletfileupload (dfif );
10 fileupload. setsizemax (50*1024*1024); // you can specify a maximum size of 50 MB for file uploading.
11
12 list <fileitem> files = fileupload. parserequest (request );
13 For (fileitem F: Files ){
14 if (F. isformfield () {// if this item is a form item, it is not a file upload item
15 out. Print (F. getfieldname ());
16 out. Print (F. getstring ("UTF-8"); // because the Web uses UTF-8 encoding, the client returns the UTF-8 encoding.
17} else {
18 string filename = f. getname ();
19 filename = filename. substring (filename. lastindexof ("."));
20 F. write (new file ("D: // upfile //" + (INT) (math. random () * 10000000) + filename); // do not learn from me, lazy Behavior
21}
22}
23} else {
24 out. Print ("the form you submitted has an error! ");
25}
Sample Code Used in a JSP
<% @ Page contenttype = "text/html; charset = GBK" Import = "Java. Io. *, java. util. *" %>
<% @ Page import = "org. Apache. commons. fileupload. *" %>
<% @ Page import = "org. Apache. commons. fileupload. servlet. *" %>
<% @ Page import = "org. Apache. commons. fileupload. disk. *" %>
<%
If (servletfileupload. ismultipartcontent (request )){
Diskfileitemfactory dfif = new diskfileitemfactory ();
Dfif. setsizethreshold (5*1024*1024); // when the memory usage exceeds 5 MB, temporary files are generated and stored in the temporary directory.
Dfif. setrepository (new file ("C: // Temp"); // you can specify the directory for storing temporary files.
Servletfileupload fileupload = new servletfileupload (dfif );
Fileupload. setsizemax (50*1024*1024); // sets the maximum size for uploading files of 50 MB.
List Files = fileupload. parserequest (request );
Iterator I = files. iterator ();
While (I. hasnext ()){
Fileitem F = (fileitem) I. Next ();
If (F. isformfield () {// if this item is a form item, it is not a file upload item
You can use the getstring method to obtain other content and then convert it.
Out. Print (F. getfieldname ());
Out. Print (F. getstring ("GBK "));
} Else {
String filename = f. getname ();
Filename = filename. substring (filename. lastindexof ("."));
F. Write (new file ("D: //" + (INT) (math. Random () * 10000000) + filename); // do not learn from me and be lazy.
}
}
} Else {
Out. Print ("the form you submitted has an error! ");
}
%>

File downloads are usually downloaded by clicking the link. Therefore, you can write the content in the servlet doget method.

File F = new file (savepath + filename );
If (F = NULL | f. Length () = 0 ){
Response. sendredirect (request. getcontextpath () + "/filenotfound. jsp"); // the file cannot be found
} Else {
Outputstream out = response. getoutputstream ();
Response. setcontenttype ("application/X-download ");
Response. setheader ("content-disposition", "attachment; filename =" + filename );
Response. setcontentlength (INT) F. Length ());
Byte [] buffer = new byte [1024];
Fileinputstream FCM = new fileinputstream (f );
Int n = 0;
While (n = FS. Read (buffer ))! =-1 ){
Out. Write (buffer, 0, N );
Out. Flush ();
}
Out. Close ();
FCM. Close ();
}

Related Article

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.