Posted on 2007-08-05 18:06
semovy 阅读(568)
评论(2) 编辑 收藏 所属分类:
struts
struts中实现文件下载的主要代码:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String strFileName = "测试文件.rar";
File file = new File("具体路径" + strFileName);//
if(file.exists()){
try{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024];
strFileName = java.net.URLEncoder.encode(strFileName, "UTF-8");//处理中文文件名的问题
strFileName = new String(strFileName.getBytes("UTF-8"),"GBK");//处理中文文件名的问题
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-rar-compressed");//不同类型的文件对应不同的MIME类型
response.setHeader("Content-Disposition","attachment; filename=" + strFileName);
OutputStream os = response.getOutputStream();
while(bis.read(buffer) > 0){
os.write(buffer);
}
bis.close();
os.close();
}
catch(Exception e){
......
}
}
return mapping.getInputForward();
}
在Struts中的实现和在ASP.NET的实现类似,这段代码就是将服务器上的文件以流的方式发送到客户端浏览器,如果要是在线打开的方式的话还应将response.setHeader("Content-Disposition","attachment; filename=" + strFileName);改写为response.setHeader("Content-Disposition","inline; filename=" + strFileName);