Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Servlets Code Examples

Simple download

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 54 55 56 57 58 59 60 61
Simple download package com.ack.web.servlet; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SimpleDownload extends HttpServlet { public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException { res.setContentType( "application/msword" ); res.setHeader( "Content-Disposition", "Attachment; Filename=testdoc.doc" ); ServletOutputStream os = res.getOutputStream(); // get resource as a url URL resourceUrl = getServletContext().getResource( "/download/testdoc.doc" ); // open connection to resource URLConnection con = null; try { con = resourceUrl.openConnection(); con.connect(); } catch( IOException ioe ) { res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to read resource: /download/testdoc.doc" ); } // set the actual content type in; must check that its non-null String contentType = con.getContentType(); if( contentType != null ) { res.setContentType( contentType ); } // send resource contents back down output stream try { InputStream is = con.getInputStream(); byte[] buf = new byte[8096]; int bytesRead; while( ( bytesRead = is.read( buf ) ) != -1 ) { os.write( buf, 0, bytesRead ); } } catch( IOException ioe ) { res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to send resource to client: /download/testdoc.doc" ); } } }