首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

在struts2中怎么实现文件的下载

2012-02-17 
在struts2中如何实现文件的下载我用struts2fileupload上传文件,把文件信息放入到数据库中,用s:iterator在

在struts2中如何实现文件的下载
我用struts2   fileupload上传文件,把文件信息放入到数据库中,用s:iterator在页面上显示上传的文件,接下来怎么实现点击文件名称进行下载。我是个新手,郁闷了一天了,希望大家帮忙解决。

[解决办法]
文件下载无非就是将指定路径下的文件读到流里面,你可以看一下文件复制是怎么做的。而且现在应该有很多控件的


/***
*
* @param pathFrom
* @param pathTo
* @return
* @throws IOException
*/
private boolean copyFile(String pathFrom,String pathTo) throws IOException
{
byte b[] = new byte[1024];
int numBytes = 0;
boolean done = false;
FileInputStream fin = null;
FileOutputStream fout = null;
File newfile = new File(pathTo);
newfile.mkdir();
try
{
fin = new FileInputStream(pathFrom);
fout = new FileOutputStream(pathTo + "/ " + "Student.xls ");
numBytes = fin.read(b);
while(!done)
{
fout.write (b,0,numBytes);
numBytes =fin.read(b);
if(numBytes== -1)
{
done= true;
}
}
return true;
}
catch(FileNotFoundException e)
{
System.out.println( "Could not find " + pathFrom + "! ");
System.out.println(e.getMessage().toString());
System.exit(0);
}
catch(Exception e)
{
System.out.println( "Usage:CopyFile X Y ");
System.exit(0);
}
return false;

}
[解决办法]
public void downloadAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {

try
{
// filename是你提交的hidden的一个文件的名字
if (!request.getParameter( "filename ").toString().trim().equals( " "))
{
String updown_path= "D:\\download ";
downLoad(updown_path+ "\\ "+request.getParameter( "filename "),response,true);
}
}
catch (Exception exp)
{
logger.error(exp);
}
}

private void downLoad(String filePath,HttpServletResponse response,boolean isOnLine)
throws Exception{
File f = new File(filePath);
if(!f.exists()){
response.sendError(404, "File not found! ");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;

response.reset(); //非常重要

if(isOnLine){ //在线打开方式

URL u = new URL( "file:/// "+filePath);

response.setContentType(u.openConnection().getContentType());

response.setHeader( "Content-Disposition ", "inline; filename= "+URLEncoder.encode(f.getName(), "UTF-8 ") );
//文件名应该编码成UTF-8
}
else{ //纯下载方式

response.setContentType( "application/x-msdownload ");
response.setHeader( "Content-Disposition ", "attachment; filename= " + URLEncoder.encode(f.getName(), "UTF-8 "));
}
OutputStream out = response.getOutputStream();
while((len = br.read(buf)) > 0)
out.write(buf,0,len);
br.close();
out.close();
}

热点排行