Enviar al cliente un fichero con Struts

2136 vistas

En la Action tendremos que recuperar el nombre del fichero a enviar (filename).
Luego se tendrá que abrirel stream del objeto response y enviarle el flujo de datos correspondiente al fichero asÃ:



java
  1. response.setContentType("multipart/zip");
  2. response.setHeader("Content-Disposition",
  3.                   "attachment; filename=\"" +
  4.                   filename.trim().substring(1,filename.length()) + "\";");
  5. response.setContentLength((int)f.length());
  6.  
  7. try
  8. {
  9.       OutputStream os = response.getOutputStream();
  10.       FileInputStream stream = new FileInputStream(f);
  11.       BufferedInputStream  bis = new BufferedInputStream(stream);
  12.       InputStream is = new BufferedInputStream(bis);
  13.       int count;
  14.       byte buf[] = new byte[4096];
  15.       while ((count = is.read(buf)) > -1)
  16.       {
  17.           os.write(buf, 0, count);
  18.       }
  19.       is.close();
  20.       os.close();
  21. }
  22. catch (Exception ex)
  23. {
  24.   ex.printStackTrace();
  25. }
  26. ..
  27. return mapping.findforward("ficheroenviado");



Esto provoca la obertura de un cuadro de diálogo pidiendo el fichero local y redirige hacia el recurso correspondiente al mapeo "ficheroenviado".