日期:2014-05-17  浏览次数:20804 次

struts2怎么将文件流发给前台
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("下载文件时参数错误");
}

servlet是这样,那么struts2里面怎么写前台才能下载到这个文件呢?

------解决方案--------------------
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; 




------解决方案--------------------
把你上面的代码放到一个action中,前台定义一个请求到这个action,就可以下载
------解决方案--------------------
你直接调用你的下载action 试试。