Solución:
Suponiendo que tenga acceso al servlet como se muestra a continuación
http://localhost:8080/myapp/download?id=7
Necesito crear un servlet y registrarlo en 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>
DownloadServlet.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();
}
}
Eso depende. Si dicho archivo está disponible públicamente a través de su servidor HTTP o contenedor de servlets, simplemente puede redirigirlo a través de response.sendRedirect()
.
Si no es así, deberá copiarlo manualmente en el flujo 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();
Deberá manejar las excepciones apropiadas, por supuesto.
Prueba con 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();
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)