[java]
<%
response.setContentType("application/x-download");//設置為下載application/x-download
String filedownload = "/要下載的文件名";//即將下載的文件的相對路徑
String filedisplay = "最終要顯示給用戶的保存文件名";//下載文件時顯示的文件保存名稱
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"%>
<%
//關於文件下載時采用文件流輸出的方式處理:
//加上response.reset(),並且所有的%>後面不要換行,包括最後一個;
response.reset();//可以加也可以不加
response.setContentType("application/x-download");
//application.getRealPath("/main/mvplayer/CapSetup.msi");獲取的物理路徑
String filedownload = "想辦法找到要提供下載的文件的物理路徑+文件名";
String filedisplay = "給用戶提供的下載文件名";
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();
//要加以下兩句話,否則會報錯
//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;
}
//這裡不能關閉
//if(outp != null)
//{
//outp.close();
//outp = null;
//}
}
%>
[java]
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<a href="do_download.jsp?url=xxxxxx">點擊下載 千千動聽</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);//禁止浏覽器打開文件 只能下載
su.downloadFile("upload/1.txt");
//out.clear();
//out=pageContext.pushBody();
%>
作者 cn_bboy