public 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="+f.getName());
//文件名应该编码成UTF-8
}
else{ //纯下载方式
response.setContentType("application/x-msdownload"); 
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName()); 
}
OutputStream out = response.getOutputStream();
while((len = br.read(buf)) >0)
out.write(buf,0,len);
br.close();
out.close();
} 这是我在网上搜到的一段文件下载的代码,
File f = new File(filePath);
if(!f.exists()){
response.sendError(404,"File not found!");
return;
}这一段的filePath到底是文件名称还是一个绝对路径呢? 我开始用了文件名称 不行 f.exists() 是false,写了绝对路径,在浏览器中也输入了这个绝对路径 文件都打开了,但是放到程序中就是不行. 注意我的这个文件名、路径啥的都是在jsp中通过js配路径出来的。不知道这样的路径放到action中能不能被准确的编辑
document.form1.action = "<%=URLUtil.generateFrameActionURL(request,true,"docUploadAction.do")%>?method=download&filePath=http://10.222.22.123/HQ/docresource/"+doc;

解决方案 »

  1.   

    method=download&filePath=http://10.222.22.123/HQ/docresource/"+doc;
    在这里你给服务器传个
    ethod=download&filePath=doc;
    然后具体完整的路径到服务器端再拼
      

  2.   

    哦 我后来是这样写的document.form1.action = "<%=URLUtil.generateFrameActionURL(request,true,"docUploadAction.do")%>?method=download&fileName="+doc;
    String fileName = request.getParameter("fileName");
    String filePath = "./docresource/"+fileName;
    File f = new File(filePath);
    //System.out.println("------=-=-=-=-=-=-=-=-="+filePath);
    //System.out.println("------=-=-=-=-=-=-=-=-="+f.getName()+"======="+f.length()+"-----------------"+f.exists());
    if( !f.exists() ){
    response.sendError(404,"File Not Found");
    return ;
    }
    结果还是404 了~~
      

  3.   

    java中将路径和文件统一叫做文件。
    也就是说,一个File的实例,可能是一个文件夹,也可能是一个文件。
    你把filePath.getAbsoluteFile()打印出来看看。
      

  4.   

    把filePath.getAbsoluteFile()打印出来看看
      

  5.   

    debug 看下filepath  看看通过地址栏直接能不能找到这个文件
      

  6.   

    打出来了 是这个  E:\CurrentProject\eclipse3.2\.\docresource\test1.doc