Serving Image from Absolute Path in Java/J2EE


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

/**
* Serving Image from Absolute Path.
*/

public class ImageServAbsolutePath extends HttpServlet {

private static final long serialVersionUID = 1L;

private static final int BUFFER_SIZE = 10240;

private String imagePath;

public void init() throws ServletException {

/*——- Image Base Path ———–*/
this.imagePath = "/images";

}

protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
// Get requested image by path info.
String requestedImage = req.getPathInfo();

// Check if file name is there in request URI.
if (requestedImage == null) {
// if file name is not there in request URI, send 404 Error, or show default image.
res.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}

// Decode the file name (might contain spaces and on) and prepare file object.
File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));

// Check if file actually exists in filesystem.
if (!image.exists()) {
// if file not exists in filesystem send 404 Error, or show default image.
res.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}

// Get content type of Image by filename.
String contType = getServletContext().getMimeType(image.getName());

// Check if file is actually an image.
if (contType == null || !contType.startsWith("image")) {
// if the file is not a real image send 404 Error, or show default image.
res.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}

// Reset servlet response.
res.reset();
res.setBufferSize(BUFFER_SIZE); //set buffer size
res.setHeader("Content-Type", contType); //set content type
res.setHeader("Content-Length", String.valueOf(image.length())); //set image size
res.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\""); //set image name

// Create streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;

try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(image), BUFFER_SIZE);
output = new BufferedOutputStream(res.getOutputStream(), BUFFER_SIZE);

// Write image contents to response.
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}

output.flush();
} finally {

if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Add the following entries to the web.xml file

<servlet>
<servlet-name>ImageServAbs</servlet-name>
<servlet-class>ImageServAbsolutePath</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ImageServAbs</servlet-name>
<url-pattern>/image/*</url-pattern>
</servlet-mapping>

HOWTO USE :

<img src="image/img.jpeg" />

Related Posts: