jeudi 18 mars 2010

J2EE : faire une servlet / un bouchon de telechargement

Pour ce projet, il faut créer un projet web, et faire un war qui sera exporté et deployer sur le serveur cible.

Voici, un exemple de code de la méthode doGet :


// TODO Auto-generated method stub
File f = new File("D:/temp/zones.pdf");
int length = 0;
ServletOutputStream op = resp.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType("D:/temp/zones.pdf");

//
// Set the response and go!
//
//
resp.setContentType((mimetype != null) ? mimetype
: "application/octet-stream");
resp.setContentLength((int) f.length());
String original_filename = "zones.pdf";
resp.setHeader("Content-Disposition", "attachment; filename=\""
+ original_filename + "\"");

//
// Stream to the requester.
//
byte[] bbuf = new byte[4096];
DataInputStream in = new DataInputStream(new FileInputStream(f));

while ((in != null) && ((length = in.read(bbuf)) != -1)) {
op.write(bbuf, 0, length);
}

in.close();
op.flush();
op.close();
}


Et voila, c'est fini, et vous obtenez une popup qui vous propose d'enregistrer le pdf.

Aucun commentaire:

Enregistrer un commentaire