Jsp页面处理不在项目目录下的文件。

最近在处理上传文件,由于上传的不在web项目目录下,所以在jsp页面用a标签直接连接地址是不可以下载的。

后来百度和谷歌了之后,大家好像说jsp页面a标签的地址,在解析的时候,会默认去web项目下面寻找。而我们

给的不是项目内的目录,所以是不会找到该文件的。

后来找到一种方法,就是a标签链接到一个jsp页面,jsp页面进行处理。通过io流处理这个文件。

方法如下:

<%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*" pageEncoding="gb2312"%><% 
/*
从链接处传入path的参数如download.jsp?path=userfile/123.jpg,download.jsp为本页JSP
注意path是tomcat下的相对路径
*/
String id=request.getParameter("id");
String temp=request.getParameter("path");
if(temp==null)
 temp="";
String path=new String(temp.getBytes("8859_1"),"gb2312");
response.reset();
response.setContentType("application/x-download");
String filenamedownload = path;
String filenamedisplay = path.substring(path.lastIndexOf("/")+1,path.length()); 
filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8"); 
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay); 
OutputStream output = null; 
FileInputStream fis = null; 
try 
    { 
        output  = response.getOutputStream(); 
        if(id.equals("1")){
           filenamedownload="/home/weblogic/documents/file/"+filenamedownload;
       
        } else if(id.equals("3")){
       
        } else{
           filenamedownload="/home/weblogic/documents/table/"+filenamedownload;
       
      }

        System.out.println("filenamedownload:"+filenamedownload);
        File file=new File(filenamedownload);
        if (!file.exists()){
          out.println("对不起,文件已删除");
          return;
        }
        fis = new FileInputStream(filenamedownload);
        
        byte[] b = new byte[1024]; 
        int i = 0; 
        while((i = fis.read(b)) > 0) 
        { output.write(b, 0, i); 
        } 
        output.flush(); 
    } 
    catch(Exception e) 
    { 
        System.out.println("Error!"); 
        e.printStackTrace(); 
    } 
    finally 
    { 
        if(fis != null) 
        { 
            fis.close(); 
            fis = null; 
        } 
        if(output != null) 
        { 
            output.close(); 
            output = null; 
        } 
    } 
%>


 

posted @ 2013-05-08 10:08  江南灬Hacker  阅读(258)  评论(0编辑  收藏  举报