Я хочу получить изображение из базы данных и отобразить его на странице JSP - PullRequest
0 голосов
/ 17 февраля 2019

Сначала у меня есть метод 'inserttimage' для вставки изображения в базу данных, а затем я использовал класс Servlet и вызвал метод 'inserttimage' для вставки операции. У меня есть свойство класса bean 'image' типа Part иЯ использовал метод установки класса бина и установил изображение, которое я получил со страницы индекса.Пожалуйста, помогите с кодом для извлечения изображения и отображения его на странице jsp

вставка изображения в базу данных

   public boolean insertimage(FoodItems food)
{
boolean result=false;
try
{
    InputStream inputstream=null;
image=food.getImage();// i have a bean class property of Part type 
    if(image !=null)
    {
        long fileSize=image.getSize();
        String  fileContent=image.getContentType();
        inputstream=image.getInputStream();
    }
    PreparedStatement pst=con.prepareStatement("insert into AvailableItems values(?)");
    pst.setBlob(1,inputstream);
    pst.executeUpdate();
    result=true;
}
catch(Exception e)
{
    System.out.println("error st Available insert"+e);
}
return result;
}

// класс сервлеров

@MultipartConfig(maxFileSize=169999999)

@WebServlet("/InsertFoods") 
    public class InsertFoods extends HttpServlet


 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 

{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
Part image=request.getPart("image");
DBOperations db=new DBOperations();
FoodItems food=new FoodItems();
food.setImage(image);
if(db.insertimage(food))
{
    response.sendRedirect("AvailableItems.jsp");
}
else
{
    pw.println("not inserted");

}
    }
}

1 Ответ

0 голосов
/ 18 февраля 2019

Предположим, у вас есть страница JSP, где вы хотите получить изображение.Вы можете сделать что-то подобное, чтобы получить любое изображение из database.

 <%   //dbconnection
          try {
                   Class.forName("com.mysql.jdbc.Driver");
                 java.sql.Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","");
                  Statement statement = conn.createStatement() ;
       resultSet=statement.executeQuery("select * from tablename") ; 
                %>
       <% while(resultSet.next()){ %> 

   Image - <img src="ImageProcess?id=<%=resultSet.getString("id")%>" width="20%"/>

    <% 
    }
    }catch(Exception e){}

    %>

В приведенном выше коде важна эта строка -> <img src="ImageProcess?id=<%=resultSet.getString("id")%>" />, здесь вы передаете parameter сервлету, чтобы получить конкретный image

Теперь, в вашем servletто есть ImageProcess Вы должны получить id в doGet и передать запрос, наконец отправить ответ на страницу JSP.

Blob image = null;
        byte[] imgData = null;
       String id= request.getParameter("id");//here you are getting id 
       int i;
       ResultSet rs =null;

 try {

            //loading drivers for mysql
           Class.forName("com.mysql.jdbc.Driver");
             Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","");


         String sql = "SELECT image FROM tablename where id=?"; //here pass that id in query to get particular image 

           PreparedStatement ps = con.prepareStatement(sql);


               ps.setString(1, id);
              rs = ps.executeQuery();    
 while (rs.next()) {
                  image = rs.getBlob("image");//getting image from database 
                  imgData = image.getBytes(1,(int)image.length()); //extra info about image
                } 

response.setContentType("image/gif");//setting response type



OutputStream o = response.getOutputStream();

o.write(imgData);//sending the image to jsp page 
o.flush();
o.close();


 }
    catch(Exception e)
         {
             e.printStackTrace();

         }

Также это не полный код, внесите изменения в соответствии сВаши требования. Также не забудьте добавить jar's file

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...