2010年3月3日 星期三

Use Servlet Download File

Source Code Refrence :

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
      
request.setCharacterEncoding("UTF-8");

String filename = (String)request.getParameter("filename");
String original_filename = (String)request.getParameter("original_filename");
                ServletOutputStream op = response.getOutputStream();
                ServletContext context  = getServletConfig().getServletContext();
                String realFileNamePath = context.getRealPath(filename);
    
File f = new File(realFileNamePath);
                int length = 0;
  
                response.setContentType("application/octet-stream");
                response.setContentLength( (int)f.length() );
                response.setHeader( "Content-Disposition",
                                                      "attachment; filename=\"" + original_filename + "\"" );

               byte[] bbuf = new byte[1024];
               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();
}

沒有留言:

張貼留言