1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
public class OuvrirFichier extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String nomFichier = req.getParameter("fic");
resp.setContentType("application/download");//types.getString("xls"));
resp.setHeader ("Content-Disposition", "attachment; filename=\""+nomFichier+"\"" );
ServletOutputStream out = resp.getOutputStream();
File file = null;
BufferedInputStream from = null;
try
{
//dans mon cas le filepath et le path complet après création d'un temp file
String realPath = this.getServletConfig().getServletContext().getRealPath("/");
file = new File(realPath+nomFichier);
resp.setContentLength((int) file.length());
int bufferSize = 64 * 1024;
long time = System.currentTimeMillis();
try {
from = new BufferedInputStream(new FileInputStream(file), bufferSize * 2);
byte[] bufferFile = new byte[bufferSize];
for (int i = 0; ; i++) {
int len = from.read(bufferFile);
if (len < 0)
break;
out.write(bufferFile, 0, len);
}
out.flush();
} finally {
try { from.close(); } catch (Exception e) { }
try { out.close(); } catch (Exception e) {}
}
time = (System.currentTimeMillis() - time) / 1000; // seconds download
double kb = (file.length() * 1.0 / 1024);
if (file != null)
file.delete();
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
try { file.delete();} catch (Exception ex) {
ex.printStackTrace();
}
}
}
} |
Partager