java - 实现一个简单的文件下载servlet

标签 java servlets download

我应该如何实现简单的文件下载servlet?

这个想法是,通过 GET 请求 index.jsp?filename=file.txt,用户可以下载例如。 file.txt 从文件 servlet 和文件 servlet 将该文件上传给用户。

我可以获取文件,但是如何实现文件下载?

最佳答案

假设您可以访问 servlet,如下所示

http://localhost:8080/myapp/download?id=7

我需要创建一个 servlet 并将其注册到 web.xml

web.xml

<servlet>
     <servlet-name>DownloadServlet</servlet-name>
     <servlet-class>com.myapp.servlet.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
     <servlet-name>DownloadServlet</servlet-name>
     <url-pattern>/download</url-pattern>
</servlet-mapping>

下载Servlet.java

public class DownloadServlet extends HttpServlet {


    protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

         String id = request.getParameter("id");

         String fileName = "";
         String fileType = "";
         // Find this file id in database to get file name, and file type

         // You must tell the browser the file type you are going to send
         // for example application/pdf, text/plain, text/html, image/jpg
         response.setContentType(fileType);

         // Make sure to show the download dialog
         response.setHeader("Content-disposition","attachment; filename=yourcustomfilename.pdf");

         // Assume file name is retrieved from database
         // For example D:\\file\\test.pdf

         File my_file = new File(fileName);

         // This should send the file to browser
         OutputStream out = response.getOutputStream();
         FileInputStream in = new FileInputStream(my_file);
         byte[] buffer = new byte[4096];
         int length;
         while ((length = in.read(buffer)) > 0){
            out.write(buffer, 0, length);
         }
         in.close();
         out.flush();
    }
}

关于java - 实现一个简单的文件下载servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1442893/

相关文章:

java - 使用 c3p0 连接池时出错

javascript - 在 HTML5 中缓存 MP3 以便离线收听?

windows - 捕获页面重定向的下载链接 (WGET)

download - XPages-xp :fileDownload Control in xp:repeat Control

java - 在Android中创建 "popup"侧边菜单

java - 日历字段增量给出了意想不到的结果

java - Android 外部 Jar

java - 从 HttpSession 检索 ArrayList 时出现无法将对象转换为 ArrayList 错误

Java 随机访问映射

java - 我应该如何在 `HttpServletRequest` 中记录发送到 `doPost` 的 `HttpServlet` 以供以后播放?