jsp下载文件

本文介绍了两种使用JSP实现文件下载的方法:一是通过RequestDispatcher方式,二是利用文件流输出进行下载。文章详细展示了如何设置HTTP响应头以指定下载文件类型及名称,并提供了具体的Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:jsp下载文件的两种方法(参见java文件的路径问题.txt ,jsp下载文件的实现方法.txt)
1. 采用RequestDispatcher的方式进行
//加上response.reset(),并且所有的%>后面不要换行,包括最后一个;
response.reset();//可以加也可以不加
String filePathValue=request.getParameter("filePath").toString();
//从action传来的是文件的相对路径
String fileName=filePathValue.substring(filePathValue.lastIndexOf("\\")+1);
//取得文件名
response.setContentType(“application/vnd.ms-excel”);
//response.setContentType(“application/x-download”);
String fileDownloadPath = “/” + filePathValue;
String fileDisplay = fileName;
fileDisplay = URLEncoder.encode(fileDisplay,”UTF-8”);
response.addHeader(“Content-Disposition”,”attachment;filename=”+fileDisplay);
try{
out.clear();
out = pageContext.pushBoby();
}catch(Exception e){
e.printStackTrace();
}
try{
RequestDispatcher dis = application.getRequestDispatcher(fileDownloadPath);
If(dis != null){
dis.forward(request,response);
}
}catch(Exception e){
e.printStackTrace();
}finally{
Response.flushBuffer();
}


可能会报java.lang.IllegalStateException: getOutputStream() has already been called for //this response的错误,原因是:response.getWriter()和response.getOutputStream()相冲突造成的.
解决办法就是:
try{
out.clear();
out = pageContext.pushBoby();
}catch(Exception e){
e.printStackTrace();
}


2. 采用文件流输出的方式下载
response.reset();//可以加也可以不加
String filePathValue=request.getParameter("filePath").toString();
//从action传来的是文件的相对路径
String fileName=filePathValue.substring(filePathValue.lastIndexOf("\\")+1);
//取得文件名
String filedownload = request.getRealPath(filePathValue);
response.setContentType(“application/vnd.ms-excel”);
//response.setContentType(“application/x-download”);
String fileDisplay = fileName;
fileDisplay = URLEncoder.encode(fileDisplay,”UTF-8”);
response.addHeader(“Content-Disposition”,”attachment;filename=”+fileDisplay);

java.io.OutputStream os = null;
java.io.InputStream is = null;
try{
os = response.getPutputStream();
is = new FileInputStream(filedownload);
byte[] buff = new byte[4096];
int result = 0;
while((result = is.read(buff)) > 0){
os.write(buff,0,result);
}
os.flush();

out.clear();
out = pageContext.pushBody();
}catch(Exception e){
e.printStackTrace();
}finally{
if(os != null){
os.closee();
os = null;
}
if(is != null){
is.close();
is = null;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值