JSP file download code share

Source: Internet
Author: User
Tags tostring tomcat tomcat server stringbuffer

JSP tutorial File download code share

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 ">
<body>
<a href= "jsp/do_download.jsp" > click to download </a>
</body>



2, download processing page do_download.jsp do_download.jsp show how to use the JSPs tutorial martupload 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 ();
Class
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");
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 ();
}

/**
* 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.

Package 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 with the Chinese name properly. 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.

Related Article

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.