Apr
15
|
Basically you stream the image to the http response stream. Easier to explain with code so here’s a simple example.
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ImageServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { ServletContext application = getServletContext(); // Get the path to image we want to return String filepath = application.getRealPath("image.gif"); // Get image MIME type String mimeType = application.getMimeType(filepath); if (mimeType == null) { application.log("Could not get MIME type of "+filepath); response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // Set content type response.setContentType(mimeType); // Set content size File file = new File(filepath); response.setContentLength((int)file.length()); // Copy the contents of the file to the responses output stream FileInputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) >= 0) { out.write(buf, 0, len); } in.close(); out.close(); } }
See also:
Leave a Reply
You must be logged in to post a comment.