簡體   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