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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1442893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:20:09  来源:igfitidea点击:

Implementing a simple file download servlet

javaservletsdownload

提问by newbie

How should I implement simple file download servlet?

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

The idea is that with the GET request index.jsp?filename=file.txt, the user can download for example. file.txtfrom the file servlet and the file servlet would upload that file to user.

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

I am able to get the file, but how can I implement file download?

我能够获取文件,但是如何实现文件下载?

采纳答案by ChssPly76

That depends. If said file is publicly available via your HTTP server or servlet container you can simply redirect to via response.sendRedirect().

那要看。如果该文件可通过您的 HTTP 服务器或 servlet 容器公开访问,您只需重定向到 via response.sendRedirect().

If it's not, you'll need to manually copy it to response output stream:

如果不是,您需要手动将其复制到响应输出流:

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();

You'll need to handle the appropriate exceptions, of course.

当然,您需要处理适当的异常。

回答by Winston Chen

The easiest way to implement the download is that you direct users to the file location, browsers will do that for you automatically.

实现下载的最简单方法是将用户定向到文件位置,浏览器会自动为您执行此操作。

You can easily achieve it through:

您可以通过以下方式轻松实现:

HttpServletResponse.sendRedirect()

回答by Ali Irawan

Assuming you have access to servlet as below

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

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

I need to create a servlet and register it to web.xml

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

web.xml

网页.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>

DownloadServlet.java

下载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();
    }
}

回答by Sorter

Try with Resource

用资源试试

File file = new File("Foo.txt");
try (PrintStream ps = new PrintStream(file)) {
   ps.println("Bar");
}
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader( "Content-Disposition",
         String.format("attachment; filename=\"%s\"", file.getName()));

OutputStream out = response.getOutputStream();
try (FileInputStream in = new FileInputStream(file)) {
    byte[] buffer = new byte[4096];
    int length;
    while ((length = in.read(buffer)) > 0) {
        out.write(buffer, 0, length);
    }
}
out.flush();