Here's some ready code for making a servlet that you can use for downloading things. Note that you will need to write the servlet itself around this piece of code.
/**
* Sends a file to the ServletResponse output stream. Typically
* you want the browser to receive a different name than the
* name the file has been saved in your local database, since
* your local names need to be unique.
*
* @param req The request
* @param resp The response
* @param filename The name of the file you want to download.
* @param original_filename The name the browser should receive.
*/
private void doDownload( HttpServletRequest req, HttpServletResponse resp,
String filename, String original_filename )
throws IOException
{
File f = new File(filename);
int length = 0;
ServletOutputStream op = resp.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType( filename );
//
// Set the response and go!
//
//
resp.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
resp.setContentLength( (int)f.length() );
resp.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );
//
// Stream to the requester.
//
byte[] bbuf = new byte[BUFSIZE];
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();
}
There are a couple of problems here:
- You should not close the outputstream
- You should close the inputstream in a finally block.
- When making a download servlet, it's a good thing to implement the getLastModified() method
Feel free to refactor; this is very old code anyway.
Modified to change "attachement" to "attachment". Found that "attachement" didn't work for me using IE6. "attachment" worked fine.
Thanks very much for this source code. It helped a lot.
--Geo, 06-Sep-2007
Here is my jsp to do the same thing.
<%@ page import= "java.io.*" %><%
BufferedReader bufferedReader=null;
try{
bufferedReader = new BufferedReader(new FileReader("somefile.zip"));
}
catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}
response.setContentType("application/zip");
String original_filename="somefile.zip";
response.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );
try{
int anInt=0;
while((anInt=bufferedReader.read())!=-1)
out.write(anInt);
}catch(IOException ioe){
ioe.printStackTrace();
}
%>
--Larry Gray
, 10-Oct-2007
Add new attachment
List of attachments
| Kind | Attachment Name | Size | Version | Date Modified | Author | Change note |
|---|---|---|---|---|---|---|
jar |
downloadPackage.jar | 5.6 kB | 1 | 29-Nov-2007 14:54 | 202.125.154.115 |