我应该如何实现简单的文件下载servlet?
这个想法是,通过GET请求index.jsp?filename=file.txt,用户可以下载例如。file.txt从文件servlet中读取,文件servlet会将文件上传给用户。
GET
index.jsp?filename=file.txt
file.txt
servlet
我可以获取文件,但是如何实现文件下载?
那要看。如果你可以通过HTTP服务器或Servlet容器公开访问该文件,则只需将其重定向到via即可response.sendRedirect()。
response.sendRedirect()
如果不是,则需要手动将其复制到响应输出流:
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();
当然,你需要处理适当的异常。
假设你可以按以下方式访问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(); } }