I am trying to display an image on jsp from local drive.
I set the img src as src = "../../../ImageServlet" in jsp but I am getting a
java.lang.IllegalStateException
at org.apache.jasper.runtime.ServletResponseWrapperInclude.getOutputStream(ServletResponseWrapperInclude.java:63)
at DisplayImageServlet.doPost(ImageServlet.java:95)
at DisplayImageServlet.doGet(ImageServlet.java:34)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
exception.
My Servlet Code is:
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
String applicationNumber = (String)session.getAttribute("APPLICATIONNUMBER");
File file = new File("C:/photos/"+applicationNumber+".jpg");
response.setContentType(getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file));
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[10240];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
and my jsp img tag is like-
<div>
<div>
<label>Photo </label>
<div>
<div style="width:194px;height:162px;"><img src="../../../ImageServlet" id="Image" style="width:100px;height:100px;" /></div>
<div style="margin-left:115px; margin-top:10px;">
<input name="filename" type="file" id="filename"/>
</div>
</div>
</div>
Please help me out or is there any other way to do the same. Thanks.
response.getOutputStream()throws the exception, rather thannew BufferedOutputStream(...). Probably the response isn't writable yet.