Upload Download Full Raiders jspsmartupload

Source: Internet
Author: User
Tags command line file size file upload header html form tostring root directory stringbuffer
js| Raiders | upload | Download One, install the article

Jspsmartupload is a fully functional file upload download component that is developed by the Www.jspsmart.com Web site and is suitable for embedding in JSP files that perform upload and download operations. This component has several features:

1, easy to use. In the JSP file just write 35 lines of Java code can be done to upload or download files, convenient.

2, can control the full upload. Using the object provided by the Jspsmartupload component and its operation method, the information of all uploaded files (including file name, size, type, extension, file data, etc.) can be obtained and conveniently accessed.

3, can upload the file in size, type and so on to make restrictions. This allows you to filter out files that do not meet your requirements.

4, download flexible. By writing only two lines of code, you can turn a Web server into a file server. Files can be downloaded using jspsmartupload, regardless of the Web server's directory or any other directory.

5, can upload the file to the database, also can download the data in the database. This functionality is for MySQL databases, because it is not generic, so this article is not going to give an example of this usage.

The Jspsmartupload component can be downloaded freely from the www.jspsmart.com website, and the name of the compressed package is jspsmartupload.zip. After downloading, extract it into Tomcat's WebApps directory with WinZip or WinRAR (described in this article as an example of Tomcat server). After decompression, the Webapps/jspsmartupload directory under the subdirectory Web-inf name changed to all uppercase Web-inf, such a change jspsmartupload class can be used. Because Tomcat is sensitive to file name capitalization, it requires that the directory of the Web application-related classes be web-inf and must be uppercase. Then restart Tomcat so that you can use the Jspsmartupload component in the JSP file.

Note that after installation as described above, only programs in the Webapps/jspsmartupload directory can use the Jspsmartupload component, and if you want all of the Tomcat server's Web applications to work with it, you must do the following:

1. Go to the command line state and switch directories to Tomcat's Webapps/jspsmartupload/web-inf directory.

2. Run Jar Pack command: jar CVF jspsmartupload.jar com

(You can also open the Resource Manager, switch to the current directory, use WinZip to compress all the files in the COM directory into Jspsmartupload.zip, and then replace the jspsmartupload.zip with the Jspsmartupload.jar file.) )

3. Copy the Jspsmartupload.jar to Tomcat's Shared/lib directory.

Second, the related class description

㈠file class

This class wraps up all the information for an uploaded file. It can get the file name, file size, extension, file data and other information of the uploaded files.

The file class mainly provides the following methods:

1, SaveAs role: To change the name of the file save.


public void SaveAs (java.lang.String destfilepathname)


public void SaveAs (java.lang.String destfilepathname, int optionsaveas)

Where Destfilepathname is a saved file name, Optionsaveas is a saved option that has three values, respectively, Saveas_physical,saveas_virtual,saveas_auto. Saveas_physical indicates that the root directory of the operating system is saved as a file root, saveas_virtual indicates that the Web application's root directory is a separate file for the file root, and Saveas_auto that the component decides When a Web application's root directory has a directory of saved files, it chooses saveas_virtual, otherwise saveas_physical is selected.

For example, SaveAs ("/upload/sample.zip", saveas_physical) is executed, and if the Web server is installed on the C disk, the saved file name is actually c:\upload\sample.zip. When SAVEAS ("/upload/sample.zip", saveas_virtual) executes, if the root directory of the Web application is Webapps/jspsmartupload, the saved file name is actually webapps/ Jspsmartupload/upload/sample.zip. SaveAs ("/upload/sample.zip", Saveas_auto) executes when the upload directory exists under the root directory of the Web application, the effect is the same as SaveAs ("/upload/sample.zip", Saveas_ VIRTUAL), otherwise with SAVEAS ("/upload/sample.zip", saveas_physical).

Recommendation: For Web application development, it is best to use saveas_virtual for porting.

2, IsMissing

Role: This method is used to determine whether the user has selected a file, i.e., whether the corresponding form item has a value. When a file is selected, it returns false. When a file is not selected, it returns True.

Prototype: public boolean ismissing ()

3, GetFieldName

Action: Takes the name of the table item in the HTML form that corresponds to this upload file.

Prototype: Public String getfieldname ()

4, GetFileName

Function: File name (excluding directory information)

Prototype: Public String GetFileName ()

5, Getfilepathname

Function: Fetch file name (with directory)

Prototype: public String Getfilepathname

6, Getfileext

Function: Take file extension (suffix)

Prototype: Public String Getfileext ()

7, GetSize

Function: Take file Length (in bytes)

Prototype: public int getsize ()

8, Getbinarydata

Function: Take a byte from the specified displacement in the file data, and use it to detect files and other processing.

Prototype: public byte getbinarydata (int index). where index represents the displacement, and its value is between 0 and GetSize ()-1.

㈡files class

This class represents the collection of all uploaded files, by which you can get information about the number, size, and so on of the uploaded files. The following methods are available:

1, GetCount

Function: Get the number of uploaded files.

Prototype: public int getcount ()

2, GetFile

Function: Gets the file object files (this is com.jspsmart.upload.File, not java.io.File, note distinction) at the specified displacement.

Prototype: public File getFile (int index). Where index is the specified displacement, and the value is between 0 and GetCount ()-1.

3, GetSize

Function: To obtain the total length of uploaded files, can be used to limit the amount of data uploaded at a one-time size.

Prototype: public long GetSize ()

4, GetCollection

Function: To return all uploaded file objects in collection form so that other applications can reference and browse the uploaded file information.

Prototype: Public Collection getcollection ()

5, GetEnumeration

Function: All uploaded file objects are returned as enumeration (enumerated) so that other applications can browse the uploaded file information.

Prototype: Public enumeration getenumeration ()

㈢request class

The functionality of this class is equivalent to the JSP built-in object request. This class is provided only because the value of the table item cannot be obtained through the request object for the file upload form, and must be obtained through the request object provided by the Jspsmartupload component. This class provides the following methods:

1, GetParameter

Function: Gets the value of the specified parameter. When a parameter does not exist, the return value is null.

Prototype: public string GetParameter (string name). Where name is the name of the parameter.

2, Getparametervalues

Function: When a parameter can have more than one value, use this method to take its value. It returns an array of strings. When a parameter does not exist, the return value is null.

Prototype: public string[] Getparametervalues (String name). Where name is the name of the parameter.

3, Getparameternames

Function: Gets the name of all parameters in the request object to traverse all parameters. It returns an object of an enumerated type.

Prototype: Public enumeration Getparameternames ()

㈣smartupload class This class completes the upload download work.

A Upload and download the common method:

Only one: Initialize.

function: Perform upload download initialization work, must be first executed.

Prototype: There are multiple, mainly using the following:

Public final void Initialize (Javax.servlet.jsp.PageContext pagecontext)

Where, PageContext is the JSP page built-in object (page context).

B How to upload files:

1, Upload

Function: Upload file data. For the upload operation, the first step is to execute the Initialize method, and the second step is to execute the method.

Prototype: public void upload ()

2, Save

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

Prototype: public int Save (String destpathname)

and public int Save (String destpathname,int option)

Where Destpathname saves the directory for the file, option is the save options, it has three values, respectively, Save_physical,save_virtual and Save_auto. (similar to the value of the option for the SaveAs method of the file class) Save_physical instructs the component to save the file to a directory with the operating system root as the root of the file, Save_virtual instructs the component to save the file to a directory with the Web application root as the root directory of the file. Save_auto, however, indicates that the component is automatically selected.

Note: The effect of Save (Destpathname) is equivalent to save (Destpathname,save_auto).

3, GetSize

Function: Take the total length of the uploaded file data

Prototype: public int getsize ()

4, GetFiles

function: Take all upload files, as the Files object form return, you can use the files class operation method to get the number of uploaded files and other information.

Prototype: Public Files GetFiles ()

5, Getrequest

Function: Get the Request object so that the value of the upload form parameter is obtained by this object.

Prototype: Public Request getrequest ()

6, Setallowedfileslist

Function: setting allows files with specified extensions to be uploaded, and the component throws an exception when the file name is not allowed in the upload process.

Prototype: public void Setallowedfileslist (String allowedfileslist)

Among them, Allowedfileslist is the list of file extensions that are allowed to be uploaded, separated by commas between the extension names. If you want to allow uploading of files that do not have an extension, you can use a two-comma representation. For example: Setallowedfileslist ("Doc,txt,,") will allow uploading of files with Doc and txt extensions and files with no extension.

7, Setdeniedfileslist

Role: Used to restrict uploading of files with the specified extension. If a file name extension is restricted, the component throws an exception when it is uploaded.

Prototype: public void Setdeniedfileslist (String deniedfileslist)

Among them, Deniedfileslist is the list of file extensions that are prohibited from uploading, and each extension is separated by commas. If you want to prohibit uploading files that do not have an extension, you can use a two comma to represent them. For example: Setdeniedfileslist ("Exe,bat,,") will prohibit uploading files with EXE and bat extensions and files without extensions.

8, Setmaxfilesize

Function: Sets the maximum length allowed for each file to be uploaded.

Prototype: public void Setmaxfilesize (long maxfilesize)

Among them, MaxFileSize is the maximum length allowed for each file to be uploaded, and will not be uploaded when the file exceeds this length.

9, Settotalmaxfilesize

Role: Set the total length of files allowed to upload, to limit the amount of data uploaded at once.

Prototype: public void Settotalmaxfilesize (long totalmaxfilesize)

Where Totalmaxfilesize is the total length of files that are allowed to be uploaded.

1, Setcontentdisposition

Action: Appends 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 the downloaded information is returned, using this method if the user needs to add additional information.

Prototype: public void Setcontentdisposition (String contentdisposition)

Where Contentdisposition is the data that you want to add. If contentdisposition is null, the component will automatically add "attachment" to indicate that the downloaded file is an attachment, and the result is that IE will prompt for the save file. Instead of automatically opening this file (ie browser generally determines what to do based on the file name extension you download, the extension doc will be opened with a Word program, the extension PDF will be opened with Acrobat program, and so on).

2, DownloadFile

function: Download the file.

Prototype: The following three prototypes are available, the first one is most commonly used, and the last two are used for file downloads in special cases (such as changing the content type, changing the saved file name).

①public void DownloadFile (String sourcefilepathname)

Where Sourcefilepathname is the name of the file to download (full name of the file with the directory)

②public void DownloadFile (String sourcefilepathname,string contentType)

Where 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-formatted file type information, which can be identified by the browser).

③public void DownloadFile (String sourcefilepathname,string contenttype,string destfilename)

Where Sourcefilepathname is the name of the file to download (the full name of the file with the directory), ContentType is the content type (MIME format file type information, can be identified by the browser), destFileName is the default save file name after downloading.

Third, File upload Chapter

㈠ form Requirements

There are two requirements for the form form for uploading files:

1, Method application post, that is, method= "post."

2, add attributes: Enctype= "Multipart/form-data"

Here is an example of the form form used to upload a file:

<form method= "POST" enctype= "Multipart/form-data"
action= "/jspsmartupload/upload.jsp" >
<input type= "FILE" name= "MYFILE" >
<input type= "SUBMIT" >

Examples of ㈡ uploads

1, upload page upload.html

This page provides the form, lets the user select to upload the file, clicks "Uploads" the button to carry on the upload operation.

Page source code is as follows:

FileName: upload.html
Author: vertical and horizontal software production center rain also odd (zhsoft88@sohu.com)
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<title> File Upload </title>
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">

<p> </p>
<p align= "center" > upload file Selection </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" >
<td><div align= "center" >1,
<input type= "FILE" name= "FILE1" size= ">"
<td><div align= "center" >2,
<input type= "FILE" name= "FILE2" size= ">"
<td><div align= "center" >3,
<input type= "FILE" name= "FILE3" size= ">"
<td><div align= "center" >4,
<input type= "FILE" name= "FILE4" size= ">"
<td><div align= "center" >
<input type= "Submit" name= "submit" value= "Upload it!" ">

2, upload processing page do_upload.jsp

This page performs file upload operations. The source of the page details the use of the upload method, this is not to repeat.

Page source code is as follows:

FileName: do_upload.jsp
Author: vertical and horizontal software production center rain also odd (zhsoft88@sohu.com)
<%@ page contenttype= "text/html; charset=gb2312 "Language=" Java "
Import= "java.util.*,com.jspsmart.upload.*" errorpage= ""%>
<title> File Upload Processing page </title>
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">

Create a new Smartupload object
Smartupload su = new Smartupload ();
Upload initialization
Su.initialize (PageContext);
Set upload limit
1. Limit the maximum length of each uploaded file.
Su.setmaxfilesize (10000);
2. Limit the length of the total upload data.
Su.settotalmaxfilesize (20000);
3. Set the file allowed to upload (by extension limit), only allow doc,txt files.
Su.setallowedfileslist ("Doc,txt");
4. Set prohibited file upload (by extension limit), no upload with Exe,bat,
Files with jsp,htm,html extensions and files that do not have extensions.
Su.setdeniedfileslist ("exe,bat,jsp,htm,html,,,");
Uploading files
Su.upload ();
Saves all uploaded files to the specified directory
int count = Su.save ("/upload");
Out.println (count+ "File Upload success! <br> ");

Use the Request object to get the value of the parameter
Out.println ("test=" +su.getrequest (). GetParameter ("TEST")
+ "<BR><BR>");

Extract upload file information, while saving files.
for (int i=0;i<su.getfiles (). GetCount (); i++)
Com.jspsmart.upload.File File = Su.getfiles (). GetFile (i);

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

Display current File information
Out.println ("<table border=1>");
OUT.PRINTLN ("<TR><TD> table item name (FieldName) </TD><TD>"
+ file.getfieldname () + "</TD></TR>");
Out.println ("<TR><TD> file length (size) </TD><TD>" +
File.getsize () + "</TD></TR>");
OUT.PRINTLN ("<TR><TD> filename (filename) </TD><TD>"
+ file.getfilename () + "</TD></TR>");
Out.println ("<TR><TD> file name 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 a file
File.saveas ("/upload/" + myfile.getfilename ());
Save to a directory with the root directory of the Web application as the root of the file
File.saveas ("/upload/" + myfile.getfilename (),
Su. Save_virtual);
Save to the operating system's root directory as the file root directory
File.saveas ("c:\\temp\\" + myfile.getfilename (),
Su. save_physical);


Four, download the paper

1, download link page download.html

Page source code is as follows:

FileName: download.html
Author: vertical and horizontal software production center rain also odd (zhsoft88@sohu.com)
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<title> Downloads </title>
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
<a href= "jsp/do_download.jsp" > click to download </a>

2, download processing page do_download.jsp do_download.jsp show how to use jspsmartupload components to download files, from the following source can be seen, download how simple.

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 ();
Su.initialize (PageContext);
Set contentdisposition NULL to prevent the browser from automatically opening the file.
Ensure that you click on the link to download the file. If not set, the downloaded file name extension is
Doc, the browser will automatically open it in Word. When the extension is PDF,
The browser will be opened with Acrobat.
Su.setcontentdisposition (NULL);
Download files
Su.downloadfile ("/upload/How to earn my first bucket of gold. Doc");

Note that the downloaded page, outside of the Java script (that is, <% ...%>), does not contain HTML code, spaces, carriage returns, or newline characters, and some words will not be downloaded correctly. If not, you can add a line break between%><% in the above source code, and then download it to ensure error. Because it affects the data stream returned to the browser, it causes parsing errors.

3. How to download Chinese files

Jspsmartupload can download files, but not enough support for Chinese. If the file name of the download has Chinese characters, then the browser prompts the saved file name, the display is a pile of garbled, very sweeping people hing. The example above is this. (This problem is also a large number of download components of the problem, very few people solve, search does not find relevant information, alas!) )

In order to increase the support for downloading Chinese files for jspsmartupload components, I have studied this component and found that the browser can display the Chinese name correctly after UTF-8 encoding the saved file name returned to the browser. This is a delightful discovery. So I have to Jspsmartupload component Smartupload class did the upgrade processing, added toutf8string This method, the change part source code 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");
if (s1.length () = = 0)
M_response.setcontenttype ("Application/x-msdownload");
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)));
if (s2.length () = = 0)
M_response.setheader ("Content-disposition",
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 ();

* Converts the Chinese characters in the file name into UTF8 encoded strings so that the saved file names are displayed correctly when downloading.
* Vertical and horizontal software production center rain also odd 2003.08.01
* @param s original filename
* @return The file name after recoding
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 The bold part of the source code, the original Jspsmartupload component of the returned file did not do any processing, and now do the conversion of the code to convert the file name to UTF-8 form of the encoding form. The UTF-8 code does not have any processing in English, and the Chinese language needs to be converted to the%xx form. In the Toutf8string method, the UTF-8 encoding of Chinese characters is obtained directly by using the encoding conversion method provided by the Java language, and then converted to the%xx form.

After compiling the source code into Jspsmartupload.jar, copy it to Tomcat's Shared/lib directory (which can be shared by all Web applications), and then restart the Tomcat server to download the file containing the Chinese name normally. Alternatively, the Toutf8string method can be used to convert hyperlinks that contain Chinese to ensure that the links are valid because some Web servers do not support Chinese links.

Summary: Jspsmartupload component is the application of JSP for B/S program development process often used in the upload download components, it is simple to use, convenient. Now I have added a file to download the Chinese name of the support, this is a powerful, will win more developers of all ages.

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.