while (rsimg.next())
{
Blob photo = rsimg.getBlob("thumbnails");
}
之后我必须做什么才能在浏览器中显示图像。
在您的
servlet
文件中尝试此代码,因为它比 jsp 更容易使用和识别错误
import java.sql.*;
import java.io.*;
public class RetrieveImage {
public static void main(String[] args) {
try{
Class.forName("YOUR DRIVER NAME");
Connection con=DriverManager.getConnection(
"URL","USERNAME","PASSWORD");
PreparedStatement ps=con.prepareStatement("select * from TBL_NAME");
ResultSet rs=ps.executeQuery();
if(rs.next()){//now on 1st row
Blob b=rs.getBlob(2); //2 means 2nd column data
byte barr[]=b.getBytes(1,(int)b.length()); //1 means first image
FileOutputStream fout=new FileOutputStream("d:\\IMG_NAME.jpg");
fout.write(barr);
fout.close();
}//end of if
System.out.println("ok");
con.close();
}catch (Exception e) {e.printStackTrace(); }
}
}
现在您可以从上面给出的路径加载图像。
希望这有帮助!
为了在网络上显示图像,您必须使用“img”标签并使用图像的相对路径填充其“src”属性。
现在的问题是,“img”标签无法将二进制数据作为“src”,即您的客户端无法直接从数据库访问文件。因此,您可以做的是,创建一个从数据库加载文件的 Servlet,然后通过 HttpServletResponse 流式传输该文件。
您的 Servlet 将如下所示:
public class DispalyImage extends HttpServlet {
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Code to access database and get blob image.
// String id = HttpServletRequest.getParameter("id");
// select from table where id='id'
Blob photo = rsimg.getBlob("thumbnails");
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("image/jpeg");
response.setHeader("Content-Length", String.valueOf(photo.length()));
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
output.close();
input.close();
}
}
}
现在的问题是,您的 Servlet 如何知道要流式传输哪个图像?只需将您的密钥作为参数提供给 Servlet 即可。该密钥将用于加载您的图像
假设您将提供密钥作为“id”,您将显示图像为
<img src="DisplayImage?id=imageId"></img>
您可以在 DisplayImage Servlet 中使用 HttpServletRequest.getParameter("id") 方法检索 id,并使用 id 从数据库加载图像。
请参阅 BalusC 的 FileServlet,其中有很好的示例和关于如何从数据库提供文件的解释。