java - 如何在servlet中显示数据库中的图像?

标签 java servlets

这段代码没有错误

import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DisplayBlobServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
            ServletException {
        String photoid = request.getParameter("txtid");
        Blob photo = null;
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String query = "select oimage from orderform where  cuname = '" + photoid + "'";
        ServletOutputStream out = response.getOutputStream();

        try {
            conn = getMySqlConnection();
        } catch (Exception e) {
            response.setContentType("text/html");
            out.println("<html><head><title>Person Photo</title></head>");
            out.println("<body><h1>Database Connection Problem.</h1></body></html>");
            return;
        }

        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(query);
            if (rs.next()) {
                photo = rs.getBlob(9);

            } else {
                response.setContentType("text/html");
                out.println("<html><head><title>Person Photo</title></head>");
                out.println("<body><h1>No photo found for id= 001 </h1></body></html>");
                return;
            }

            response.setContentType("image/gif");
            InputStream in = photo.getBinaryStream();
            int length = (int) photo.length();

            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];

            while ((length = in.read(buffer)) != -1) {
                System.out.println("writing " + length + " bytes");
                out.write(buffer, 0, length);
            }

            in.close();
            out.flush();
        } catch (SQLException e) {
            response.setContentType("text/html");
            out.println("<html><head><title>Error: Person Photo</title></head>");
            out.println("<body><h1>Error=" + e.getMessage() + "</h1></body></html>");
            return;
        } finally {
            try {
                rs.close();
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /*private static Connection getHSQLConnection() throws Exception {
    Class.forName("jdbc.jdbcDriver");
    System.out.println("Driver Loaded.");
    String url = "jdbc:hsqldb:data/tutorial";
    return DriverManager.getConnection(url, "sa", "");
    }*/
    public static Connection getMySqlConnection() throws Exception {
        String driver = "com.jdbc.mysql.Driver";
        String url = "jdbc:mysql://localhost/studio";
        String username = "root";
        String password = " ";

        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
    }

    /*public static Connection getOracleConnection() throws Exception {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:databaseName";
    String username = "username";
    String password = "password";

    Class.forName(driver); // load Oracle driver
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
    }*/
}

最佳答案

您需要告诉用户的浏览器该内容是图像:

response.setContentType("image/jpg")

否则浏览器将尝试将字节流显示为文本。 但由于您没有指定您遇到的“错误”,我目前无法提供任何进一步的帮助。

关于java - 如何在servlet中显示数据库中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4848819/

相关文章:

java - 如何使用正则表达式允许连字符

java - com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E : [Servlet Error]-[faces]: java. lang.NullPointerException

java - 为什么一个web容器可以管理一个servlet?

java.sql.SQLIntegrityConstraintViolationException : Cannot add or update a child row: a foreign key constraint fails

java - 加载应用程序时出现异常 : java. lang.IllegalStateException : ContainerBase. addChild : start: org. apache.catalina.LifecycleException:

java - 如何将 javascript 变量传递给 java servlet?

java - 无法通过servlet代码在tomcat服务器上上传文件

java - 使用收集器按两个字段进行分组

java - 从 IType 实例化对象

Java 8 通用函数映射