![](/img/trans.png)
[英]How to display an image from a database in a JSP using a java servlet?
[英]How to display image on jsp from DB using java servlet
我想要做的基本上是在jsp頁面上顯示來自Mysql的圖像。 我能夠使用以下代碼成功地將 blob 圖像文件調用到我的 java servlet 中的輸出流中。
在 servlet 中,
byte[] imgData = null;
Blob image1 = null;
image1 = result.getBlob("image1");
imgData = image1.getBytes(1, (int)image1.length());
在jsp中,
<%
response.setContentType("image/gif");
OutputStream o = response.getOutputStream();
o.write(imgData);
%>
這種方法的問題是這個jsp頁面是用圖像完成的。 這樣,頁面會丟棄其他內容,只顯示圖像。 我想要做的是使用
<img src=??? width=??? height=???>
我試圖調整輸出流圖像的大小,但我認為沒有辦法。
請幫我
提前致謝。
在我看來,您應該創建兩個不同的 servlet:
一種用於通過從HttpServlet
獲取寫入器並寫入字節數組作為響應來下載圖像。
二, .jsp
頁面將包含一個img
標簽, src
將鏈接到第一個端點。
這看起來像:
1)
public class ImageServlet extends HttpServlet {
//...
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
//...
response.setHeader("Content-Type", this.getServletContext().getMimeType(imageFileName));
response.setHeader("Content-Length", X);
response.getOutputStream().write(<<image byte[]>>);
}
2)
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %>
<html>
<head><title>Hello</title></head>
<body bgcolor="white">
<img src="/images?id=3" height="Xpx" width="Ypx">
<h2>My name is Duke. What is yours?</h2>
</body>
</html>
我認為這應該有效。 如果答案有幫助,請投票作為接受的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.