Showing posts with label file download in java. Show all posts
Showing posts with label file download in java. Show all posts

Wednesday, March 13, 2013

comment_icon 2 File Download Script For JSP

In this Tutorial  i'm going to explain how you can serve files to your users using JSP. Since we are not serving a HTML page so first we need to tell the browser that what kind of data we are going to serve for that we set Response Headers
 response.addHeader( "Content-Disposition","attachment; filename=your file name" );
Here application/msword is the mime type you can search internet for diff. mime type required for  diff. extensions few commonly used are
  • image/jpeg
  • text/plain
  • application/pdf

link format for filedownload

<a href="download.jsp?filename=myresume.doc">Download my resume</a>


<%@ page  import="" %>
<%@ page  import=""  %>
<%@ page  import=""  %>
<%@ page import="" %>


   // you  can get your base and parent from the database
   String base="file";
   String filename=request.getParameter("filename");
// you can  write http://localhost
   String filepath="http://localhost:8080/filedownload/"+base+"/";

BufferedInputStream buf=null;
   ServletOutputStream myOut=null;


myOut = response.getOutputStream( );
     File myfile = new File(filepath+filename);
     //set response headers
        "Content-Disposition","attachment; filename="+filename );

     response.setContentLength( (int) myfile.length( ) );
     FileInputStream input = new FileInputStream(myfile);
     buf = new BufferedInputStream(input);
     int readBytes = 0;

     //read from the file; write to the ServletOutputStream
     while((readBytes = )) != -1)

} catch (IOException ioe){
        throw new ServletException(ioe.getMessage( ));
     } finally {
     //close the input/output streams
         if (myOut != null)
             myOut.close( );
          if (buf != null)
          buf.close( );


Project Structure

Download zip