JSP Image Upload to Database



Below I have a code that should accept a user’s uploaded image in the form of an input element and push it to a MySQL Database. I am using Tomcat 9. Why is it not working yet no exceptions are being thrown? Nothing is being pushed to the database and there is no way of telling to what point the code is being executed. Note that I have embedded the class within the jsp file as IntelliJ has issues with separate servlet classes. Also note that the code was influenced by BalusC’s answer. If possible, could anyone suggest an alternative code that can be used instead?

<form action="trial4.jsp" method="post" enctype="multipart/form-data">
    <input type="text" name="description"/>
    <input type="file" name="file"/>
    <input type="submit"/>
</form>
<%!
static String URL = "localhost:3306/";
    static String DATABASE_NAME = "MYDB";
    static String USERNAME = "user";
    static String PASSWORD = "";

    @WebServlet("/upload")
    @MultipartConfig
    public class UploadServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            try {
                String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
                Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
                String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
                InputStream fileContent = filePart.getInputStream();
                // ... (do your job here)

                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection("jdbc:mysql://" + URL + DATABASE_NAME, USERNAME, PASSWORD);
                PreparedStatement ps = con.prepareStatement("insert into data(image) values(?)");
                ps.setBinaryStream(1, fileContent);
                ps.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
%>

Answer

For other people who may face/are facing a similar challenge, there is a repo that has really helped. The repo owner deserves a cup of coffee.



Source: stackoverflow