¿Cómo debo implementar el servlet de descarga de archivos simple?
La idea es que con la solicitud GET index.jsp?filename=file.txt
, el usuario puede descargar, por ejemplo. file.txt
desde el servlet de archivo y el servlet de archivo cargaría ese archivo al usuario.
Puedo obtener el archivo, pero ¿cómo puedo implementar la descarga de archivos?
Eso depende. Si dicho archivo está disponible públicamente a través de su servidor HTTP o contenedor de servlets, simplemente puede redireccionar a través de response.sendRedirect()
.
Si no es así, deberá copiarlo manualmente a la secuencia de salida de respuesta:
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();
Necesitarás manejar las excepciones apropiadas, por supuesto.
Asumiendo que tienes acceso al servlet como abajo
http://localhost:8080/myapp/download?id=7
Necesito crear un servlet y registrarlo en web.xml
web.xml
DownloadServlet com.myapp.servlet.DownloadServlet DownloadServlet /download
DescargarServlet.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(); } }
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();
La forma más fácil de implementar la descarga es que dirige a los usuarios a la ubicación del archivo, los navegadores lo harán automáticamente.
Puedes lograrlo fácilmente a través de:
HttpServletResponse.sendRedirect()
@WebServlet("/download") public class DownloadFileServlet extends HttpServlet{ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ String fileName = "pdf-sample.pdf"; FileInputStream fileInputStream = null; OutputStream responseOutputStream = null; try { String filePath = request.getServletContext().getRealPath("/WEB-INF/resources/")+ fileName; File file = new File(filePath); String mimeType = request.getServletContext().getMimeType(filePath); if (mimeType == null) { mimeType = "application/octet-stream"; } response.setContentType(mimeType); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentLength((int) file.length()); fileInputStream = new FileInputStream(file); responseOutputStream = response.getOutputStream(); int bytes; while ((bytes = fileInputStream.read()) != -1) { responseOutputStream.write(bytes); } } catch(Exception ex) { ex.printStackTrace(); } finally { fileInputStream.close(); responseOutputStream.close(); } } }
Referencia: descargar archivo de una aplicación web con Servlet