Berthou.comA french developper blog | |
|
This article aims at presenting how to create a servlet that sends a zip file to the user. We create here a html page with a form where you can enter an url. The servlet will get the content of this url (only the html page, not the images or other frames), create a zip file with it, and send you the file.
li>Creating a zip file Have you ever noticed the java.util.zip package ?
zout.putNextEntry(new ZipEntry("file.html"));
zout.write(b,0,size);
zout.closeEntry();
zout.finish();
String zip=bout.toString();
package javaside.servlet.sample ; /** * zipservlet.java * * Main class for sample servlet * * @author : R. BERTHOU * URL : http://www.berthou.com/ * ----------------------------------------------------------- * Ver * Author * DATE * Description * ....................DD/MM/YY............................... * 1.00 * R.BERTHOU * 12/01/01 * **********************************************************/ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.zip.*; import java.net.*; import java.util.*; public class zipservlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { byte b[]=new byte[300000]; URL url; String temp; ByteArrayOutputStream bout=new ByteArrayOutputStream(); ZipOutputStream zout=new ZipOutputStream(bout); ServletOutputStream out = res.getOutputStream(); ServletContext servletContext = getServletContext(); if ((temp=req.getParameter("url"))!=null) { try { url=new URL(temp); URLConnection uc = url.openConnection(); DataInputStream input = new DataInputStream(uc.getInputStream()); int numRead=0; int size=0; while (numRead != -1) { numRead = input.read(b,size,20000); size+=numRead; } zout.putNextEntry(new ZipEntry("file.html")); zout.write(b,0,size); zout.closeEntry(); zout.finish(); String zip=bout.toString(); res.setContentType("application/zip"); res.setHeader("Content-Disposition","inline; filename=output.zip;"); out.println(zip); out.flush(); } catch (Exception e) { res.setContentType("text/html"); out.println("<html><head></head>"); out.println("<body><b>"); out.println("An error has occured while processing "+temp+""); out.println("Here is the exception: "+e+""); e.printStackTrace(new PrintWriter(out)); out.println("</body>"); out.println("</html>"); } } } } |
CategoriesTagsRecent PostsRecent Comments
|
|
| |
2 Responses pour"Servlet : zipservlet"
Hey,
its a nice post. was very useful when I was googling especially for the “fileName” part ;).
Thanks. keep up the good work.
Cheers,
Raghavan alias Saravanan M.
[...] The thread which helped me in getting the complete stuff was -> http://www.berthou.com/us/2007/09/29/test-english/ and http://forums.sun.com/thread.jspa?threadID=486951 page_revision: 8, last_edited: [...]
Ajouter une réponse