Wyswietlanie zdjec z bazy jsp

0

Hej, mam problem z wyświetlaniem zdjęć z bazy(blob) na stronie jsp

package controller;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/Add")
@MultipartConfig(maxFileSize = 16177215)   
public class AddNew extends HttpServlet {


      private String dbURL = "jdbc:mysql://localhost:3306/mydb";
        private String dbUser = "root";
        private String dbPass = "";

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



     String FirstName = request.getParameter("FirstName");   
     String LastName = request.getParameter("LastName");     
     String Email = request.getParameter("Email");



        InputStream inputStream1 = null; // input stream of the upload file
        InputStream inputStream2 = null;
        InputStream inputStream3 = null;
        InputStream inputStream4 = null;


        Part Photo1 = request.getPart("Photo1");
        Part Photo2 = request.getPart("Photo2");
        Part Photo3 = request.getPart("Photo3");
        Part Photo4 = request.getPart("Photo4");
        if (Photo1 != null && Photo2 !=null && Photo3 !=null && Photo4 !=null ) {


            inputStream1 = Photo1.getInputStream();
            inputStream2 = Photo2.getInputStream();
            inputStream3 = Photo3.getInputStream();
            inputStream4 = Photo4.getInputStream();
        }

        Connection conn = null; 
        String message = null;  

        try {

            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            conn = DriverManager.getConnection(dbURL, dbUser, dbPass);


            String sql = "INSERT INTO users (FirstName, LastName,Email, Photo1, Photo2, Photo3, Photo4) values (?, ?, ?,?, ?, ?,?)";
            PreparedStatement statement = conn.prepareStatement(sql);

            statement.setString(1, FirstName);
            statement.setString(2, LastName);
            statement.setString(3, Email);

            if (inputStream1 != null && inputStream2 != null && inputStream3 != null && inputStream4 != null  ) {

                statement.setBlob(4, inputStream1);
                statement.setBlob(5, inputStream2);
                statement.setBlob(6, inputStream3);
                statement.setBlob(7, inputStream4);

            }



            int row = statement.executeUpdate();
            if (row > 0) {
                message = "File uploaded and saved into database";

            }
        } catch (SQLException ex) {
            message = "ERROR: " + ex.getMessage();
            ex.printStackTrace();
        } finally {
            if (conn != null) {

                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }

            request.setAttribute("Message", message);


            getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
        }
    }
}

Wszystko śmiga, do bazy dodaje zdjęcie



package controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SearchUsers extends HttpServlet {

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


        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "mydb";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "";



        Statement st;
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, userName, password);
            System.out.println("Connected!");
            String Name = request.getParameter("Name");

            ArrayList al = null;
            ArrayList Name_list = new ArrayList();              
            String query = "select FirstName, LastName,Email, Photo1, Photo2, Photo3, Photo4 from users where Name='" + Name + "' ";


            st = conn.createStatement();
            ResultSet rs = st.executeQuery(query);

            while (rs.next()) {
                al = new ArrayList();
                al.add(rs.getString(1));
                al.add(rs.getString(2));
                al.add(rs.getString(3));





                System.out.println("al :: " + al);
                Name_list.add(al);
            }

            request.setAttribute("piList", Name_list);
            RequestDispatcher view = request.getRequestDispatcher("/ViewUsers.jsp");
            view.forward(request, response);
            conn.close();
            System.out.println("Disconnected!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
<%@ page import="java.util.*" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">



<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
        <table width="1200px" align="center" enctype="multipart/form-data"
               style="border:1px solid #000000;">
            <tr>
                <td colspan=5 align="center"
                    style="background-color:teal">
                    <b></b></td>
            </tr>
            <tr style="background-color:lightgrey;">
                <td><b>First Name</b></td>
                <td><b>Last Name</b></td>
                <td><b>Email</b></td>
                <td><b>Photo1</b></td>
                <td><b>Photo2</b></td>
                <td><b>Photo3</b></td>
                <td><b>Photo4</b></td>


            </tr>
            <%
                int count = 0;
                String color = "#F9EBB3";
                if (request.getAttribute("piList") != null) {
                    ArrayList al = (ArrayList) request.getAttribute("piList");
                    System.out.println(al);
                    Iterator itr = al.iterator();
                    while (itr.hasNext()) {

                        if ((count % 2) == 0) {
                            color = "#eeffee";
                        }
                        count++;
                        ArrayList pList = (ArrayList) itr.next();
            %>
            <tr style="background-color:<%=color%>;">
                <td><%=pList.get(0)%></td>
                <td><%=pList.get(1)%></td>
                <td><%=pList.get(2)%></td>




            </tr>
            <%
                    }
                }
                if (count == 0) {
            %>
            <tr>
                <td colspan=4 align="center"
                    style="background-color:#eeffee"><b>Nope</b></td>
            </tr>
            <%            }
            %>
        </table>
    </body>
</html>

Wrzuciłem kod bez moich mizernych prób wyświetlenia zdjęcia, pomóżcie dobrzy ludzie :O

2

Nigdy:

String query = "select FirstName, LastName,Email, Photo1, Photo2, Photo3, Photo4 from users where Name='" + Name + "' ";
tak

nie

rób.

Nawet dla zabawy.

PreparedStatement jeśli już.

Wyświetlanie zrób servletem, który renderuje strumień - a w jsp użyj <img src="tenServlet?user=X&photo=3"/>

tak jak mniej więcej tu:
http://stackoverflow.com/questions/4848819/how-to-display-image-from-database-in-servlet

0

Albo zrobisz ze content tego zdjęcia będzie base 64 i wtedy jak tu http://stackoverflow.com/questions/1207190/embedding-base64-images

Lub zrób servlet który dostanie idika zdjęcia do pokazania i jego zawartość wypluje jako OutputStream + nagłówki

<img src="http://locsalhost:8080/app/image?id=12" />
0

Właśnie mi się urodziło w głowie, czy nie lepiej byłoby zrobić to na zasadzie zapisywania do bazy ścieżki do zdjęcia, to nie musiałbym wtedy robić osobnego servletu z wyświetlaniem zdjęć. Znalazłem coś takiego http://stackoverflow.com/questions/27090246/how-to-download-file-from-files-path-stored-in-mysql-by-using-servlet-jsp

Tylko nie rozkminiam czy dla każdego zdjęcia muszę to robić osobno ?

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.