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 decompression, change the Web-inf name in the subdirectory 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 the drive c, the actual file name stored in the 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)
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.
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> </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 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.