Use the jspsmartupload component to upload and download files

Source: Internet
Author: User
Tags mime file ranges

I. Installation

Jspsmartupload is a free-of-charge, full-featured file upload and download component developed by www.jspsmart.com. It is suitable for embedding JSP files for uploading and downloading. This component has the following features:

1. Easy to use. You can easily upload or download files by writing only three or five lines of Java code in JSP files.

2. Full upload control. The objects provided by the jspsmartupload component and their operation methods can be used to obtain information about all uploaded files (including file names, sizes, types, extensions, and file data) for easy access.

3. restrict the size and type of uploaded files. This filters out non-conforming files.

4. Flexible download. Only two lines of code can be written to convert the Web server into a file server. You can use jspsmartupload to download files in the web server directory or any other directory.

5. You can upload files to the database or download data from the database. This function is intended for MySQL databases, because it is not universal, so this article does not prepare examples to introduce this usage.

The jspsmartuploadgroup can be freely downloaded from www.jspsmart.com. the name of the compressed package is jspsmartupload.zip. After the download, use WinZip or WinRAR to decompress it to the webapps directory of Tomcat (this article takes the Tomcat server as an example ). After unzipping, change the name of the child ke yieb-INF under the webapps/jspsmartupload directory to a fully capitalized WEB-INF so that the jspsmartupload class can be used. Because Tomcat is case sensitive to file names, it requires that the directory of classes related to Web applications be WEB-INF and must be in uppercase. Restart tomcat to use the jspsmartupload component in the JSP file.

Note: After installation as described above, only programs under the webapps/jspsmartupload directory can use the jspsmartupload component. To make all web applications of the Tomcat server use the jspsmartupload component, you must do the following:

1. Go to the command line status and switch the directory to the Tomcat webapps/jspsmartupload/WEB-INF directory.

2. Run the jar packaging command: jar CVF jspsmartupload. Jar com

You just need to change the keystore name to the jspsmartupload. jar file .)

3. Copy jspsmartupload. jar to the shared/lib directory of Tomcat.

Ii. Related Categories

(I) File class

This class encapsulates all the information of an uploaded file. You can obtain the file name, file size, extension, file data, and other information of the uploaded file.

The file class mainly provides the following methods:

1. saveas: Replace the file with another name.

Prototype:

Public void saveas (Java. Lang. String destfilepathname)

Or

Public void saveas (Java. Lang. String destfilepathname, int optionsaveas)

Here, destfilepathname is the name of another stored file, and optionsaveas is the option of another stored. This option has three values: saveas_physical, saveas_virtual, and saveas_auto. Saveas_physical indicates that the root directory of the operating system is the root directory of the file and the root directory of the file. saveas_virtual indicates that the root directory of the Web application is the root directory of the file, and saveas_auto indicates that the component is determined, when the root directory of the Web application has another directory for storing files, it will select saveas_virtual; otherwise, it will select saveas_physical.

For example, after saveas ("/upload/sample.zip", saveas_physical) is executed, if the web server is installed on disk C, the actual file name stored in another file is C:/upload/sample.zip. However, after saveas ("/upload/sample.zip", saveas_virtual) is executed, if the root directory of the Web application is webapps/jspsmartupload, the actual file name is webapps/jspsmartupload/upload/sample.zip. Saveas ("/upload/sample.zip", saveas_auto) if the web application root directory contains the upload directory, the effect is the same as saveas ("/upload/sample.zip", saveas_virtual ), otherwise, it is the same as saveas ("/upload/sample.zip", saveas_physical ).

Suggestion: for web program development, it is best to use saveas_virtual for porting.

2. ismissing

Purpose: This method is used to determine whether a file is selected, that is, whether the corresponding form item has a value. If a file is selected, false is returned. If the file is not selected, true is returned.

Prototype: Public Boolean ismissing ()

3. getfieldname

Purpose: Obtain the name of the form item corresponding to the uploaded file in the HTML form.

Prototype: Public String getfieldname ()

4. getfilename

Purpose: get the file name (excluding the directory information)

Prototype: Public String getfilename ()

5. getfilepathname

Purpose: Take the full name of the file (with directory)

Prototype: Public String getfilepathname

6. getfileext

Purpose: Obtain the file extension (suffix)

Prototype: Public String getfileext ()

7. getsize

Purpose: take the file length (in bytes)

Prototype: Public int getsize ()

8. getbinarydata

Purpose: Take a byte of the specified displacement in the file data for file detection and other processing.

Prototype: Public byte getbinarydata (INT index ). Here, index indicates the displacement, and its value ranges from 0 to getsize ()-1.

(Ii) files

This class indicates a collection of all uploaded files. You can obtain information such as the number and size of uploaded files. You can use the following methods:

1. getcount

Purpose: obtain the number of uploaded files.

Prototype: Public int getcount ()

2. GetFile

Purpose: Obtain the file object file at the specified displacement (this is com. jspsmart. Upload. file, not Java. Io. file. Note the difference ).

Prototype: Public file GetFile (INT index ). Here, index is the specified displacement, and its value ranges from 0 to getcount ()-1.

3. getsize

Purpose: Get the total length of the uploaded file, which can be used to limit the size of the data uploaded at a time.

Prototype: Public long getsize ()

4. getcollection

Purpose: return all uploaded file objects in the form of collections so that other applications can reference and browse the uploaded file information.

Prototype: public collection getcollection ()

5. getenumeration

Purpose: return all uploaded file objects in the form of enumeration (enumeration), so that other applications can browse the uploaded file information.

Prototype: Public enumeration getenumeration ()

(Iii) Request class

The function of this class is equivalent to the built-in JSP Object Request. Only this class is provided because the value of the form item cannot be obtained through the request object for file upload forms. It must be obtained through the request object provided by the jspsmartupload component. This class provides the following methods:

1. getparameter

Purpose: obtain the value of a specified parameter. If the parameter does not exist, the return value is null.

Prototype: Public String getparameter (string name ). Here, name is the parameter name.

2. getparametervalues

Purpose: use this method to obtain the value of a parameter if it can have multiple values. It returns a string array. If the parameter does not exist, the return value is null.

Prototype: Public String [] getparametervalues (string name ). Here, name is the parameter name.

3. getparameternames

Purpose: Obtain the names of all parameters in the request object and traverse all parameters. It returns an enumerated object.

Prototype: Public enumeration getparameternames ()

(4) The smartupload class completes upload and download.

A. Shared upload and download methods:

Only one: Initialize.

Purpose: perform the initialization of upload/download. The first task is required.

Prototype: there are multiple, mainly using the following:

Public final void initialize (javax. servlet. jsp. pagecontext)

Pagecontext is a built-in JSP page object (page context ).

B. How to upload files:

1. Upload

Purpose: Upload File data. For the upload operation, the first step is to execute the initialize method, and the second step is to execute this method.

Prototype: Public void upload ()

2. Save

Purpose: Save all uploaded files to the specified directory and return the number of saved files.

Prototype: Public int save (string destpathname)

And public int save (string destpathname, int option)

Destpathname is the file storage directory, and option is the storage option. It has three values: save_physical, save_virtual, and save_auto. (Similar to the value of the saveas method in the file class) save_physical indicates that the component saves the file to the directory where the root directory of the operating system is the root directory of the file, save_virtual indicates that the component saves the file to the directory where the root directory of the Web application is used as the root directory, while save_auto indicates that the component selects the file automatically.

Note: Save (destpathname) is equivalent to save (destpathname, save_auto ).

3. getsize

Purpose: obtain the total length of the uploaded file data.

Prototype: Public int getsize ()

4. getfiles

Purpose: retrieve all uploaded files and return them as files objects. You can use the files operation method to obtain the number of uploaded files and other information.

Prototype: public files getfiles ()

5. getrequest

Purpose: Obtain the request object to obtain the value of the upload form parameter.

Prototype: public request getrequest ()

6. setallowedfileslist

Purpose: Set whether to upload a file with the specified extension. When a file name is not allowed during the upload process, the component throws an exception.

Prototype: Public void setallowedfileslist (string allowedfileslist)

Allowedfileslist is the list of file extensions that can be uploaded. Each extension is separated by a comma. To upload files without an extension, use two commas. For example, setallowedfileslist ("Doc, txt,") allows you to upload files with the doc and TXT extensions and files without the extension.

7. setdeniedfileslist

Purpose: restrict the upload of files with the specified extension. If the file extension is limited, the component throws an exception during upload.

Prototype: Public void setdeniedfileslist (string deniedfileslist)

Deniedfileslist is a list of file extensions that are not allowed to be uploaded. Each extension is separated by a comma. To prohibit the upload of files without an extension, use two commas. For example, setdeniedfileslist ("EXE, bat,") will prohibit the upload of files with EXE and bat extensions and files without extension extensions.

8. setmaxfilesize

Purpose: set the maximum length of each file that can be uploaded.

Prototype: Public void setmaxfilesize (long maxfilesize)

Maxfilesize is the maximum length that each file can upload. When the file length exceeds this length, it is not uploaded.

9. settotalmaxfilesize

Purpose: set the total length of the file that can be uploaded to limit the size of the data volume for one-time upload.

Prototype: Public void settotalmaxfilesize (long totalmaxfilesize)

Totalmaxfilesize indicates the total length of the file to be uploaded.

C. Common Methods for downloading files

1. setcontentdisposition

Purpose: append data to the content-Disposition field of the MIME file header. The jspsmartupload component automatically fills in the Content-Disposition field of the MIME file header when returning the downloaded information. If you need to add additional information, use this method.

Prototype: Public void setcontentdisposition (string contentdisposition)

Here, contentdisposition is the data to be added. If contentdisposition is null, the component automatically adds "attachment;" to indicate that the downloaded file is used as an attachment. The result is that the IE browser will prompt you to save the file, instead of opening the file automatically (ie usually decides what to do based on the downloaded file extension. If the extension is Doc, it will be opened by the word program, and if the extension is PDF, It will be opened by the acrobat program, and so on ).

2. downloadfile

Purpose: download an object.

Prototype: The following three prototypes are available: the first one is the most commonly used, and the last two are used for downloading files in special circumstances (such as changing the content type and changing the file name of another storage ).

① Public void downloadfile (string sourcefilepathname)

Among them, sourcefilepathname is the name of the file to be downloaded (full name of the file with directory)

② Public void downloadfile (string sourcefilepathname, string contenttype)

Among them, sourcefilepathname is the name of the file to be downloaded (the full name of the file with the Directory), and contenttype is the content type (MIME format file type information, which can be recognized by the browser ).

③ Public void downloadfile (string sourcefilepathname, string contenttype, string destfilename)

Among them, sourcefilepathname is the name of the file to be downloaded (the full name of the file with the Directory), contenttype is the content type (MIME format file type information, which can be recognized by the browser ), destfilename is the default file name for storing files after downloading.

Iii. File Upload

(I) Form requirements

There are two requirements for the Form for uploading files:

1. Apply post to method, that is, method = "Post ".

2. Add attributes: enctype = "multipart/form-Data"

The following is an example of a form used to upload files:

<Form method = "Post" enctype = "multipart/form-Data"
Action = "/jspsmartupload/upload. jsp">
<Input type = "file" name = "myfile">
<Input type = "Submit">
</Form>

(Ii) Upload example

1、upload page upload.html

This page provides a form that allows you to select the file to be uploaded and click "Upload" to upload the file.

The page source code is as follows:

<! --
File Name: upload.html
Author: Landscape software production center Yu Yiqi (zhsoft88@sohu.com)
-->
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> File Upload </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
</Head>

<Body>
<P> & nbsp; </P>
<P align = "center"> select an upload file </P>
<Form method = "Post" Action = "JSP/do_upload.jsp"
Enctype = "multipart/form-Data">
<Input type = "hidden" name = "test" value = "good">
<Table width = "75%" border = "1" align = "center">
<Tr>
<TD> <Div align = "center"> 1,
<Input type = "file" name = "file1" size = "30">
</Div> </TD>
</Tr>
<Tr>
<TD> <Div align = "center"> 2,
<Input type = "file" name = "file2" size = "30">
</Div> </TD>
</Tr>
<Tr>
<TD> <Div align = "center"> 3,
<Input type = "file" name = "file3" size = "30">
</Div> </TD>
</Tr>
<Tr>
<TD> <Div align = "center"> 4,
<Input type = "file" name = "file4" size = "30">
</Div> </TD>
</Tr>
<Tr>
<TD> <Div align = "center">
<Input type = "Submit" name = "Submit" value = "upload it! ">
</Div> </TD>
</Tr>
</Table>
</Form>
</Body>
</Html>

2. Upload processing page do_upload.jsp

Upload files on this page. The page source code details the usage of the upload method, which will not be repeated here.

The page source code is as follows:

<% --
File Name: do_upload.jsp
Author: Landscape software production center Yu Yiqi (zhsoft88@sohu.com)
-- %>
<% @ Page contenttype = "text/html; charset = gb2312" Language = "Java"
Import = "Java. util. *, Com. jspsmart. Upload. *" errorpage = "" %>
<HTML>
<Head>
<Title> File Upload processing page </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
</Head>

<Body>
<%
// Create a new smartupload object
Smartupload su = new smartupload ();
// Upload Initialization
Su. initialize (pagecontext );
// Set upload restrictions
// 1. Limit the maximum length of each uploaded file.
// Su. setmaxfilesize (10000 );
// 2. Restrict the total length of uploaded data.
// Su. settotalmaxfilesize (20000 );
// 3. Set the files that can be uploaded (with the extension limit). Only the doc and TXT files are allowed.
// Su. setallowedfileslist ("Doc, TXT ");
// 4. Set files that are not allowed to be uploaded (by using the extension limit). Upload with EXE, bat, is prohibited,
JSP, htm, HTML extension files and files without extension.
// Su. setdeniedfileslist ("EXE, bat, JSP, htm, HTML ,,");
// Upload a file
Su. Upload ();
// Save all uploaded files to the specified directory
Int COUNT = Su. Save ("/upload ");
Out. println (count + "files uploaded successfully! <Br> ");

// Obtain the parameter value using the request object
Out. println ("test =" + su. getrequest (). getparameter ("test ")
+ "<Br> ");

// Extract the uploaded file information one by one and save the file.
For (INT I = 0; I <Su. getfiles (). getcount (); I ++)
{
Com. jspsmart. Upload. File file = Su. getfiles (). GetFile (I );

// Continue if the object does not exist
If (file. ismissing () continue;

// Display the current file information
Out. println ("<Table border = 1> ");
Out. println ("<tr> <TD> form Item Name (fieldname) </TD> <TD>"
+ File. getfieldname () + "</TD> </tr> ");
Out. println ("<tr> <TD> file size </TD> <TD>" +
File. getsize () + "</TD> </tr> ");
Out. println ("<tr> <TD> file name (filename) </TD> <TD>"
+ File. getfilename () + "</TD> </tr> ");
Out. println ("<tr> <TD> file extension (fileext) </TD> <TD>"
+ File. getfileext () + "</TD> </tr> ");
Out. println ("<tr> <TD> file full name (filepathname) </TD> <TD>"
+ File. getfilepathname () + "</TD> </tr> ");
Out. println ("</table> <br> ");

// Save the file
// File. saveas ("/upload/" + myfile. getfilename ());
// Save it to the directory where the root directory of the Web application is the root directory of the file.
// File. saveas ("/upload/" + myfile. getfilename (),
Su. save_virtual );
// Save the file to the root directory of the Operating System
// File. saveas ("C: // temp //" + myfile. getfilename (),
Su. save_physical );

}
%>
</Body>
</Html>

Iv. File Download

1、download link page download.html

The page source code is as follows:

<! --
File Name: download.html
Author: Landscape software production center Yu Yiqi (zhsoft88@sohu.com)
-->
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> download </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
</Head>
<Body>
<A href = "JSP/do_download.jsp"> click to download </a>
</Body>
</Html>

2. the download processing page do_download.jsp shows how to use the jspsmartupload component to download files. The following source code shows how to download files easily.

The source code is as follows:

<% @ Page contenttype = "text/html; charset = gb2312"
Import = "com. jspsmart. Upload. *" %> <%
// Create a new smartupload object
Smartupload su = new smartupload ();
// Initialization
Su. initialize (pagecontext );
// Set contentdisposition to null to prevent the browser from automatically opening the file,
// Ensure that the object is downloaded after the link is clicked. If this parameter is not set, the downloaded file name extension is
// When the doc is used, the browser automatically opens it with word. When the extension is PDF,
// The browser will be opened with Acrobat.
Su. setcontentdisposition (null );
// Download an object
Su. downloadfile ("/upload/For example, pick up my first bucket of gold .doc ");
%>

Note that the page for executing the download is out of the Java Script range (that is, <%.... If you do not believe it, you can add a line break between %> <% in the source code and download it again to ensure that an error occurs. It affects the data streams returned to the browser, resulting in parsing errors.

3. How to download Chinese files

Although jspsmartupload can download files, it does not support Chinese characters. If the downloaded file name contains Chinese characters, the browser displays a bunch of garbled characters when prompted for another file name. The above example is as follows. (This problem also exists in many download components, which is rarely solved and relevant information cannot be found. Sorry !)

In order to add support for downloading Chinese files to the jspsmartupload component, I studied this component and found that after the UTF-8 code of the file name returned to the browser is performed, the browser can display the Chinese name correctly. This is a happy discovery. So I upgraded the smartupload class of the jspsmartupload component and added the toutf8string method. The source code of some changes is as follows:

Public void downloadfile (string S, string S1, string S2, int I)
Throws servletexception, ioexception, smartuploadexception
{
If (S = NULL)
Throw new illegalargumentexception ("file" + S +
"'Not found (1040 ).");
If (S. Equals (""))
Throw new illegalargumentexception ("file" + S +
"'Not found (1040 ).");
If (! Isvirtual (s) & m_denyphysicalpath)
Throw new securityexception ("physical path is
Denied (1035 ).");
If (isvirtual (s ))
S = m_application.getrealpath (s );
Java. Io. File file = new java. Io. file (s );
Fileinputstream = new fileinputstream (File );
Long L = file. Length ();
Boolean flag = false;
Int K = 0;
Byte abyte0 [] = new byte [I];
If (S1 = NULL)
M_response.setcontenttype ("application/X-msdownload ");
Else
If (s1.length () = 0)
M_response.setcontenttype ("application/X-msdownload ");
Else
M_response.setcontenttype (S1 );
M_response.setcontentlength (INT) L );
M_contentdisposition = m_contentdisposition! = NULL?
M_contentdisposition: "attachment ;";
If (s2 = NULL)
M_response.setheader ("content-disposition ",
M_contentdisposition + "filename =" +
Toutf8string (getfilename (s )));
Else
If (s2.length () = 0)
M_response.setheader ("content-disposition ",
M_contentdisposition );
Else
M_response.setheader ("content-disposition ",
M_contentdisposition + "filename =" + toutf8string (S2 ));
While (long) k <L)
{
Int J = fileinputstream. Read (abyte0, 0, I );
K + = J;
M_response.getoutputstream (). Write (abyte0, 0, J );
}
Fileinputstream. Close ();
}

/**
* Convert the Chinese characters in the file name into UTF-8 encoded strings so that another file name can be correctly displayed during download.
* Landscape software production center Yu Yiqi 2003.08.01
* @ Param s original file name
* @ Return the reencoded file name
*/
Public static string toutf8string (string s ){
Stringbuffer sb = new stringbuffer ();
For (INT I = 0; I <S. Length (); I ++ ){
Char c = S. charat (I );
If (C> = 0 & C <= 255 ){
SB. append (C );
} Else {
Byte [] B;
Try {
B = character. tostring (c). getbytes ("UTF-8 ");
} Catch (exception ex ){
System. Out. println (Ex );
B = new byte [0];
}
For (Int J = 0; j <B. length; j ++ ){
Int K = B [J];
If (k <0) K + = 256;
SB. append ("%" + integer. tohexstring (k ).
Touppercase ());
}
}
}
Return sb. tostring ();
}

Note that in the bold part of the source code, the original jspsmartupload component does not do any processing of the returned file, now do the conversion of the encoding work, the file name into the UTF-8 form of encoding. The UTF-8 Code does not take any action on the English language, and the Chinese language needs to be converted to the form of % xx. In toutf8string method, the UTF-8 encoding of Chinese characters is obtained directly by using the encoding conversion method provided by Java language, and then converted to the form of % xx.

Compile the source code and package it into jspsmartupload. jar, copy it to the Tomcat shared/lib directory (which can be shared by all web applications), and restart the Tomcat server to download files containing Chinese names. In addition, the toutf8string method can also be used to convert hyperlinks containing Chinese characters to ensure the link is valid, because some Web servers do not support Chinese links.

Summary: The jspsmartupload component is a frequently used upload/download component during B/S program development by Using JSP. It is easy to use and convenient. Now I have added support for downloading files with Chinese names. This is a huge addition and will surely win the favor of more developers.

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.