[Java]
<%
Response. setContentType ("application/x-download"); // set it to download application/x-download
String filedownload = "/file name to be downloaded"; // relative path of the file to be downloaded
String filedisplay = "the name of the file to be saved to the user"; // The name of the file to be saved when the file is downloaded
String filenamedisplay = URLEncoder. encode (filedisplay, "UTF-8 ");
Response. addHeader ("Content-Disposition", "attachment; filename =" + filedisplay );
Try
{
RequestDispatcher dis = application. getRequestDispatcher (filedownload );
If (dis! = Null)
{
Dis. forward (request, response );
}
Response. flushBuffer ();
}
Catch (Exception e)
{
E. printStackTrace ();
}
Finally
{
}
%>
[Javascript]
<% @ Page language = "java" contentType = "application/x-msdownload" pageEncoding = "gb2312" %>
<%
// When downloading an object, use the file stream output method:
// Add response. reset (), and do not wrap all %>, including the last one;
Response. reset (); // either or not
Response. setContentType ("application/x-download ");
// Application. getRealPath ("/main/mvplayer/CapSetup. msi"); physical path obtained
String filedownload = "find the physical path + file name of the file to be downloaded ";
String filedisplay = "download file name provided to users ";
String filedisplay = URLEncoder. encode (filedisplay, "UTF-8 ");
Response. addHeader ("Content-Disposition", "attachment; filename =" + filedisplay );
Java. io. OutputStream outp = null;
Java. io. FileInputStream in = null;
Try
{
Outp = response. getOutputStream ();
In = new FileInputStream (filenamedownload );
Byte [] B = new byte [1024];
Int I = 0;
While (I = in. read (B)> 0)
{
Outp. write (B, 0, I );
}
//
Outp. flush ();
// Add the following two sentences. Otherwise, an error is returned.
// Java. lang. IllegalStateException: getOutputStream () has already been called for // this response
Out. clear ();
Out = pageContext. pushBody ();
}
Catch (Exception e)
{
System. out. println ("Error! ");
E. printStackTrace ();
}
Finally
{
If (in! = Null)
{
In. close ();
In = null;
}
// Cannot be disabled here
// If (outp! = Null)
//{
// Outp. close ();
// Outp = null;
//}
}
%>
[Java]
<% @ Page language = "java" import = "java. util. *" pageEncoding = "GBK" %>
<A href = "do_download.jsp? Url = xxxxxx "> click to download thousands of beautiful pictures </a>
<% @ Page language = "java" import = "java. util. *" pageEncoding = "GBK" %>
<% @ Page import = "com. jspsmart. upload. SmartUpload" %>
<%
SmartUpload su = new SmartUpload ();
Su. initialize (pageContext );
Su. setContentDisposition (null); // disable the browser to open files and download only
Su. downloadFile ("upload/1.txt ");
// Out. clear ();
// Out = pageContext. pushBody ();
%>
Author: cn_bboy