我正在尝试在本地驱动器的jsp上显示图像。
我在imp中将img src设置为src = "../../../ImageServlet"
,但我得到了一个
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)
异常。
我的Servlet代码是:
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();
}
}
和我的jsp img标签就像 -
<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>
请帮帮我,还是有其他方法可以做同样的事。 感谢。
答案 0 :(得分:2)
@ user3035077尝试以下代码..
try {
HttpSession session=request.getSession();
String applicationNumber = (String)session.getAttribute("APPREFNUMBER");
File file = new File("C:/photos/"+applicationNumber+".jpg");
if (file.exists()) {
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(file));
// Get image contents.
byte[] bytes = new byte[in.available()];
in.read(bytes);
in.close();
// Write image contents to response.
response.getOutputStream().write(bytes);
}
} catch (IOException e) {
e.printStackTrace();
}
如果这有帮助,请告诉我......