How do I serve a file?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   James_Johnson
Posted On:   Friday, November 22, 2002 07:21 AM

I want to have a servlet or jsp serve a file on my hard drive. The file will not be in the tomcat directory, or at least not in the webapps directory.

I want the file to not be directly linked to so I can check to see if a session variable exists first, and then serve the file.

If anyone has code examples of this, I would be eternally greateful if you could direct me to it. Namely servlet code that serves a file back to the requestor.


Thanks in advance.

James

Re: How do I serve a file?

Posted By:   Lasse_Koskela  
Posted On:   Friday, November 22, 2002 09:23 AM

This should be close (I haven't compiled/tested):

import javax.servlet.http.*;
import java.io.*;

/**
* Serves a file from the disk.
*/
public class FileServlet
{
/**
* Receives and responds to requests.
*/
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
Boolean serveFiles = (Boolean) req.getSession(true).getAttribute("serveFiles");
if (serveFiles != null && serveFiles.booleanValue())
{
InputStream fis = null;
OutputStream out = res.getOutputStream();
String filename = req.getParameter("filename");
fis = new BufferedInputStream(
new FileInputStream(filename));

byte[] buffer = new byte[1024];
int bytes = -1;
while ((bytes = fis.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, bytes));
}

res.close();
}
else
{
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("

");
out.println("File cannot be served at the moment");
out.println("

");
}
}
}
About | Sitemap | Contact