下载文件

//从站点上下载文件

public File download(HttpServletRequest request,
HttpServletResponse response){
LogSearchDTO logSearchDTO = (LogSearchDTO)request.getSession().getAttribute(SessionNameResolver.getLogSearch());
String path;
if(logSearchDTO != null){
path = this.createExcel(this.find(logSearchDTO));
}else{
path = this.createExcel(this.find(request.getParameter("vid")));
}
InputStream inputStream = null;
ServletOutputStream servletOutputStream = null;
File file;
try {
response.reset();
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment; filename="
+ "auditLogs.xls");
servletOutputStream = response.getOutputStream();
file = new File(path);
inputStream = new FileInputStream(file);
byte[] by = new byte[2048];
int len = 0;
while ((len = inputStream.read(by)) > 0) {
servletOutputStream.write(by, 0, len);
}
inputStream.close();
servletOutputStream.flush();
servletOutputStream.close();
servletOutputStream = null;
response.flushBuffer();

} catch (Exception e) {
logger.error(e);
return null;
} finally {
if (inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
}
}

if (servletOutputStream != null)
try {
servletOutputStream.close();
} catch (IOException e) {

}
}
return file;
}

jsp上的写法,否则会出错:

<%--
COPYRIGHT Avetti.com Corporation 1998-2007. All Rights Reserved
--%>
<%@ page contentType="text/html;charset=utf-8"%>
<%@ page language = "java" import="java.io.*,org.apache.log4j.Logger"%><%
out.clear();
out=pageContext.pushBody();
Object fobj = session.getAttribute("files");
File f =null;
if(fobj != null){
f = (File)fobj;
session.removeAttribute("files");
}
if(f != null) {
try{
InputStream inStream=new FileInputStream(f);
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition","attachment; filename="+f.getName());
byte [] b = new byte[1024];
int len = 0;
ServletOutputStream sos = response.getOutputStream();
while((len=inStream.read(b)) >0) {
sos.write(b,0,len);
}
inStream.close();
sos.flush();
sos.close();

}catch(IOException ioe){
Logger logger = Logger.getLogger(getClass());
logger.info("error in downloadfileBA : "+ioe);
}
}else{
out.write("<script language='javascript'>alert('File do not exist,please export it first');window.history.go(-1);</script>");
}
%>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值