在jsp中的特定文件夹上下载文件

时间:2014-09-17 03:50:10

标签: jsp download directory

我已经尝试并使用JSP

测试从服务器下载任何文件到客户端PC

但我关心的是如何下载一个特定的文件夹,下面是我目前的代码:

 <%@page import="java.io.FileInputStream"%>
 <%@page import="java.io.OutputStream"%>
 <%@page import="java.io.FileOutputStream"%>
 <%@page import="java.io.BufferedOutputStream"%>
 <%@page import="java.io.BufferedInputStream"%>
 <%@page import="java.io.File"%>
 <%@page import="java.io.IOException"%>
 <%@page import="java.io.FileReader"%>
 <%@page import="java.io.FileWriter"%>
 <%@page import="java.io.BufferedReader"%>

<%  
    String filename = "K:\\gcache/rispacs.net/267/1.2.392.200036.9125.9.0.319792973.175747576.2790676870.dcm";
    response.setContentType("application/octet-stream");
    String disHeader = "Attachment; Filename=\"test.dcm\"";
    response.setHeader("Content-Disposition", disHeader);
    File fileToDownload = new File(filename);
    System.out.print("1");

    InputStream ins = null;
    ServletOutputStream outs = response.getOutputStream();  

    int name =  filename.lastIndexOf("/");
    String format = filename.substring(name);

    try {
        ins = new BufferedInputStream(new FileInputStream(fileToDownload));

        FileOutputStream fos = new FileOutputStream("C:\\dcmsyst/cache/"+format);
        int ch;
        while ((ch = ins.read()) != -1) {
        outs.print((char) ch);
        }



    }
    finally {
    if (ins != null) ins.close(); // very important
    }

    outs.flush();
    outs.close();
    ins.close();    
%>

它现在正在运行,但下载到指定文件夹的文件是0KB。

2 个答案:

答案 0 :(得分:0)

要在java中下载文件,您必须将内容写入响应,在您的代码中,您只需要写入服务器中的另一个文件夹。由于内容类型设置为application/octet-stream,因此您将获得一个空文件。要下载文件,您必须执行以下操作

OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(fileToDownload);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) != -1){
    out.write(buffer, 0, length);
}
in.close();
out.flush();

  

但我关心的是如何下载特定文件夹

这是浏览器设置无法在服务器端完成的。

答案 1 :(得分:0)

此代码正常运行。你可以尝试

 response.setContentType("APPLICATION/OCTET-STREAM");
 response.setHeader("Content-Disposition","attachment; filename=\""+fileName);
 FileOutputStream out = new FileOutputStream(fileObject+"\\"+fileName);
 FileInputStream fileInputStream=new FileInputStream(paths);
 int i;
 while((i=fileInputStream.read())!=-1)
 {
   out.write(i);
 }
 fileInputStream.close(); 
 out.flush();