Descargar un fichero desde un servlet

2017 vistas

Veamos un ejemplo que permite descargar un fichero desdel servidor hacia el cliente:



java
  1. resp.setContentType("application/download");
  2. resp.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
  3.  
  4. ServletOutputStream out = resp.getOutputStream();
  5. File file = null;
  6. BufferedInputStream from = null;
  7. try {
  8.   // en este ejemplo, filepath es el path completo después de la creación de un fichero temporal
  9.   file = new File(filepath);
  10.   resp.setContentLength((int) file.length());
  11.   int bufferSize = 64 * 1024;
  12.   long time = System.currentTimeMillis();
  13.   try {
  14.     from = new BufferedInputStream(new FileInputStream(file), bufferSize * 2);
  15.     byte[] bufferFile = new byte[bufferSize];
  16.     for (int i = 0; ; i++) {
  17.       int len = from.read(bufferFile);
  18.       if (len < 0) break;
  19.       out.write(bufferFile, 0, len);
  20.     }
  21.     out.flush();
  22.   } finally {
  23.     try { from.close(); } catch (Exception e) { }
  24.     try { out.close(); } catch (Exception e) {} }
  25.   time = (System.currentTimeMillis() - time) / 1000; // segundos download
  26.   double kb = (file.length() * 1.0 / 1024);
  27.   if (file != null) file.delete();
  28. } catch (Exception e) {
  29.   return;
  30. } finally {
  31.   try { file.delete();} catch (Exception ex) {}
  32. }