while (rsimg.next())
{
Blob photo = rsimg.getBlob("thumbnails");
}
之后,我必须做什么才能在浏览器中显示图像。如何在jsp中检索mysql数据库中的blob图像
while (rsimg.next())
{
Blob photo = rsimg.getBlob("thumbnails");
}
之后,我必须做什么才能在浏览器中显示图像。如何在jsp中检索mysql数据库中的blob图像
试试这个代码在你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。关键就可以用来加载图像
假设你提供了关键的“身份证”,你将显示图像作为
<img src="DisplayImage?id=imageId"></img>
可以使用HttpServletRequest.getParameter(“ID”)方法获取ID您的DisplayImage Servlet并使用该ID从数据库加载图像。
参考FileServlet by BalusC,它有很好的例子和解释如何从数据库提供文件。