I want to upload an Image and then display it on JSP.
Here's my servlet
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
Part filePart = request.getPart("photo");
if (filePart != null) {
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres?currentSchema=test", "postgres",
"password");
System.out.println(conn);
String sql = "INSERT INTO personal_data (first_name, last_name, photo) values (?, ?, bytea(?))";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBinaryStream(3, inputStream);
}
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (Exception ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
request.setAttribute("Message", message);
request.getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
My data gets stored successfully into the database, I need some reference or code for retrieval of
byteaimage and displaying it onMessage.jsp
If you could help, please suggest some reference or provide some piece of code.
Thanks in advance.