繁体   English   中英

我想从数据库中检索图像并在JSP中使用显示它 <img> 标签。 我正在使用我的SQL

[英]I want to retrieve image from database and display it in JSP using <img> tag. I am using my sql

我想从数据库中检索图像,并使用img标签在JSP中显示它。 我正在使用mySql。

public class DisplayImage extends  HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //PrintWriter pw = response.getWriter();
        String connectionURL = "jdbc:mysql://localhost:3306/demodb";;
        java.sql.Connection con=null;
        try{  
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con=DriverManager.getConnection(connectionURL,"root","0321");  
            Statement st1=con.createStatement();
            ResultSet rs1 = st1.executeQuery("select photo from contacts where  contact_id='2'");
            String imgLen="";
            if(rs1.next()){
                imgLen = rs1.getString(1);
                System.out.println(imgLen.length());
            }  
            rs1 = st1.executeQuery("select photo from contacts where contact_id='2'");
            if(rs1.next()){
                int len = imgLen.length();
                byte [] rb = new byte[len];
                InputStream readImg = rs1.getBinaryStream(1);
                int index=readImg.read(rb, 0, len);  
                System.out.println("index"+index);
                st1.close();
                response.reset();
                response.setContentType("image/jpg");
                response.getOutputStream().write(rb,0,len);
                response.getOutputStream().flush();  
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}    

此代码直接显示图像。 但是我要走这条路。 所以我可以在任何地方显示它。 还有其他方法可以在动态网页中显示此图像吗?

路径取决于您的servlet在web.xml中的映射方式(因为我在代码中看不到任何注释)。 另一种方法(但不建议使用)是使用数据URI。 请参阅我要使用servlet从mysql数据库中检索图像,并在表中显示该图像以及该用户的详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM