//从站点上下载文件
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>");
}
%>