繁体   English   中英

从特定文件夹下载文件的Servlet?

[英]Servlet for download files from a specific folder?

我是JAVA技术的新手,特别是Servlets。我需要创建一个Web应用程序项目,它有一个上传和下载文件到服务器(tomcat)。我已经有一个上传servlet,工作正常。

我还有一个在互联网上找到的下载servlet。但问题是这个servlet只允许下载一个特定的文件,并且在servlet中给出了这个特定文件的路径。 我需要让客户端查看我的上传文件夹的全部内容,并从该文件夹中选择要下载的文件。

下载servlet的代码是这样的:

import java.io.DataInputStream; 
import java.io.File; 
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletContext; 
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



 public class DownloadServlet extends javax.servlet.http.HttpServlet implements
            javax.servlet.Servlet {
        static final long serialVersionUID = 1L;
        private static final int BUFSIZE = 4096;
        private String filePath;`

public void init() {
    // the file data.xls is under web application folder

    filePath = getServletContext().getRealPath("")  + File.separator;// + "data.xls";
}

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    File file = new File(filePath);
    int length   = 0;
    ServletOutputStream outStream = response.getOutputStream();
    ServletContext context  = getServletConfig().getServletContext();
    String mimetype = context.getMimeType(filePath);

    // sets response content type
    if (mimetype == null) {
        mimetype = "application/octet-stream";
    }
    response.setContentType(mimetype);
    response.setContentLength((int)file.length());
    String fileName = (new File(filePath)).getName();

    // sets HTTP header
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    byte[] byteBuffer = new byte[BUFSIZE];
    DataInputStream in = new DataInputStream(new FileInputStream(file));

    // reads the file's bytes and writes them to the response stream
    while ((in != null) && ((length = in.read(byteBuffer)) != -1))
    {
        outStream.write(byteBuffer,0,length);
    }

    in.close();
    outStream.close();
}
}

JSP页面是这样的:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Download Servlet Test</title>
</head>
<body>
Click on the link to download: <a href="DownloadServlet">Download Link</a>
</body>
</html>

我搜索了很多servlet,但所有这些都是这样的......他们只允许下载一个特定的文件。 谁能帮我? 非常感谢你!

由于您正在处理doGet方法上的数据,因此可以将参数传递给servlet,您可以在其中指明要下载的文件的名称。 为此,您应该假定文件名存在于基本路径中。 代码可能是这样的:

HTML

<body>
    Click on the link to download:
    <a href="DownloadServlet?fileName=data.xls">Download Link</a>
</body>

Java Servlet代码:

protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    //retrieving the parameter by its name
    String fileName = request.getParameter("fileName"); //this will return `data.xls`
    //using the File(parent, child) constructor for File class
    File file = new File(filePath, fileName);
    //verify if the file exists
    if (file.exists()) {
        //move the code to download your file inside here...

    } else {
        //handle a response to do nothing
    }
}

请注意,由于代码现在使用File(String parent, String child)构造函数,因此filePath不应再包含分隔符(这将由Java处理):

public void init() {
    // the file data.xls is under web application folder
    filePath = getServletContext().getRealPath("");
}

你可以这样做

     public void doGet(HttpServletRequest req, HttpServletResponse res){
     res.setContentType("text/html);
      PrintWriter out=response.getWriter();
      String fileName="home.txt";
      String filePath="d:\\";
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition","attachment;fileName=\""+fileName+"\"");
    int i;
    FileInputStream file=new FileInputStream(filePath +fileName);
    while((i=file.read()) !=-1){
      out.write(i);
   }
    file.close();
   out.close();
}
  // get MIME type of the file
    String mimeType = context.getMimeType(fullPath);
    if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }
    System.out.println("MIME type: " + mimeType);

    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

这个更详细的问题以及如何改进的问题: https//stackoverflow.com/questions/41914092/how-change-servlet-which-download-single-file-but-can-folderfew-files-in-fold

暂无
暂无

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

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