js| Raiders | upload | download
One, installation 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.
Prototype:
public void SaveAs (java.lang.String destfilepathname)
Or
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 classThis 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.
B. Common ways to download files
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:
ffffff cellpadding=2 width=540 align=center bordercolorlight=black border=1>
<form method= "POST" enctype= "Multipart/form-data" action= "/jspsmartupload/upload.jsp" ><INPUT "FILE" Name= "MYFILE" ><input type= "SUBMIT" ></FORM>
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" >
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=" "%>
Four, download the paper
1, download link page download.html
Page source code is as follows:
<!--filename: download.html : Vertical and horizontal software production center rain also odd (zhsoft88@sohu.com)--><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
2, download the processing page do_download.jspDo_download.jsp shows how to use the Jspsmartupload component 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 ();//Initialize Su.initialize (PageContext); Set contentdisposition NULL to prevent the browser from automatically opening the file,//guaranteed to click on the link is the download file. If not set, the browser will automatically open it in Word when the downloaded file name extension is//doc. When the extension is PDF, the//browser opens with Acrobat. Su.setcontentdisposition (null);//download File 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 Aby te0[] = new Byte[i];if (S1 = = null) m_response.setcontenttype ("Application/x-msdownload"); ElseIf (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)) ); ElseIf (s2.length () = 0) M_response.setheader ("Content-disposition", m_contentdisposition); else M_response.set Header ("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 character in the file name into a UTF8 encoded string so that the saved file name is displayed correctly when downloading. * Vertical and horizontal software production center rain also odd 2003.08.01 * @param s original filename * @return recoding filename/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.