<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: servlet code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 25 Jul 2008 08:39:33 GMT</pubDate>
    <description>DZone Snippets: servlet code</description>
    <item>
      <title>Example file download servlet</title>
      <link>http://snippets.dzone.com/posts/show/4629</link>
      <description>// description of your code here&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;  /**&lt;br /&gt;     *  Sends a file to the ServletResponse output stream.  Typically&lt;br /&gt;     *  you want the browser to receive a different name than the&lt;br /&gt;     *  name the file has been saved in your local database, since&lt;br /&gt;     *  your local names need to be unique.&lt;br /&gt;     *&lt;br /&gt;     *  @param req The request&lt;br /&gt;     *  @param resp The response&lt;br /&gt;     *  @param filename The name of the file you want to download.&lt;br /&gt;     *  @param original_filename The name the browser should receive.&lt;br /&gt;     */&lt;br /&gt;    private void doDownload( HttpServletRequest req, HttpServletResponse resp,&lt;br /&gt;                             String filename, String original_filename )&lt;br /&gt;        throws IOException&lt;br /&gt;    {&lt;br /&gt;        File                f        = new File(filename);&lt;br /&gt;        int                 length   = 0;&lt;br /&gt;        ServletOutputStream op       = resp.getOutputStream();&lt;br /&gt;        ServletContext      context  = getServletConfig().getServletContext();&lt;br /&gt;        String              mimetype = context.getMimeType( filename );&lt;br /&gt;&lt;br /&gt;        //&lt;br /&gt;        //  Set the response and go!&lt;br /&gt;        //&lt;br /&gt;        //&lt;br /&gt;        resp.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );&lt;br /&gt;        resp.setContentLength( (int)f.length() );&lt;br /&gt;        resp.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );&lt;br /&gt;&lt;br /&gt;        //&lt;br /&gt;        //  Stream to the requester.&lt;br /&gt;        //&lt;br /&gt;        byte[] bbuf = new byte[BUFSIZE];&lt;br /&gt;        DataInputStream in = new DataInputStream(new FileInputStream(f));&lt;br /&gt;&lt;br /&gt;        while ((in != null) &amp;&amp; ((length = in.read(bbuf)) != -1))&lt;br /&gt;        {&lt;br /&gt;            op.write(bbuf,0,length);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        in.close();&lt;br /&gt;        op.flush();&lt;br /&gt;        op.close();&lt;br /&gt;    }&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 09 Oct 2007 23:12:04 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4629</guid>
      <author>frost137 (Douglas Wyatt)</author>
    </item>
  </channel>
</rss>
