繁体   English   中英

J2EE:如何下载文件?

[英]J2EE : how to download a file?

我目前有一个JSP页面,其中包含文件列表,我想通过单击列表中的此名称来下载每个文件。 我的JSP代码:

    <c:forEach var="listFiles" items="${listFiles}" varStatus="status">
       <span id="file-${status.index}" class="files">
           <a href="Download">
              <c:out value="${listFiles[status.index]}"></c:out>
           </a>
    </c:forEach>

我为我的servlet找到了一个运行的函数,但这是一个简单的示例,其中我们将路径文件提供给servlet,我希望此代码是通用的。 如何将每个路径文件提供给servlet?

将此代码放在您的servlet中:

String filename=null;

try
{
    filename = request.getParameter("filename");        

    if(filename == null || filename.equals(""))
    {
        throw new ServletException("File Name can't be null or empty");
    }

    String filepath = "yourDirPath"+filename;   //change your directory path

    File file = new File(filepath);
    if(!file.exists())
    {
        throw new ServletException("File doesn't exists on server.");
    }

    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\""); 

    java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath);

    int i; 
    while ((i=fileInputStream.read()) != -1) 
    {
         response.getWriter().write(i); 
    } 
    fileInputStream.close();
}
catch(Exception e)
{
    System.err.println("Error while downloading file["+filename+"]"+e);
}

可以说您的servlet网址模式是: download

现在,您用于下载文件的html代码应如下所示:

<a href="download?filename=YourFileName" target="_blank">Click here to download file</a>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM