日期:2014-05-17 浏览次数:21061 次
String path=request.getParameter("path");//从页面获取要下载的文件的相对路径
			if(!"".equals(path)){
				path=new String(path.getBytes("ISO-8859-1"),"UTF-8");
				File file=new File(getServletContext().getRealPath("/")+path);//构造要下载的文件	
				if(file.exists()){
					InputStream ins=new FileInputStream(getServletContext().getRealPath("/")+path);//构造一个读取文件的IO流对象
					BufferedInputStream bins=new BufferedInputStream(ins);//放到缓冲流里面
					OutputStream outs=response.getOutputStream();//获取文件输出IO流
					BufferedOutputStream bouts=new BufferedOutputStream(outs);
					response.setContentType("application/x-download");//设置response内容的类型
					response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(path, "UTF-8"));//设置头部信息
					int bytesRead = 0;
					byte[] buffer = new byte[8192];
					//开始向网络传输文件流
					while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
						bouts.write(buffer, 0, bytesRead);
					}
					bouts.flush();//这里一定要调用flush()方法
					ins.close();
					bins.close();
					outs.close();
					bouts.close();
				}else{
					System.out.println("下载的文件不存在");
				}
			}else{
				System.out.println("下载文件时参数错误");
			}public String execute() throws Exception { 
	// 文件下载目录路径 
	String downloadDir = ServletActionContext.getServletContext().getRealPath("/download"); 
	// 文件下载路径 
	String downloadFile = ServletActionContext.getServletContext().getRealPath(inputPath); 
	java.io.File file = new java.io.File(downloadFile); 
	downloadFile = file.getCanonicalPath();// 真实文件路径,去掉里面的..等信息 
	// 发现企图下载不在 /download 下的文件, 就显示空内容 
	if(!downloadFile.startsWith(downloadDir)) { 
		return null; 
	} 
	return SUCCESS; 
}