Jspsmartupload User Guide 2

Source: Internet
Author: User

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:
<! 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:
<% @ 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:
<! 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.