exceptionservletsfilenotfoundexceptionservletexceptionojdbc

FileNotFoundException uploading an image to Oracle database


I have made a servlet program to insert image into an Oracle database. The program is as follows.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InsertImage extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String url=request.getParameter("image");
        File image=new File(url);
        FileInputStream fis;
        PrintWriter pw=response.getWriter();
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String str = "jdbc:oracle:thin:@localhost:1521:XE";
            Connection con = DriverManager.getConnection(str,"system","root");
            PreparedStatement pstmt=con.prepareStatement("insert into insertimage(image) values(?)");
            fis = new FileInputStream(image);
            pstmt.setBinaryStream(1, (InputStream)fis, (int)(image.length()));
            int size=pstmt.executeUpdate();
            if(size>0)
            {
                pw.println("<html>Image Uploaded Successfully.</html>");
            }
            else
            {
                pw.println("<html>Image could not be uploaded.</html>");
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
        catch(ClassNotFoundException e)
        {
            e.printStackTrace();
        }
    }
}

And the HTML page, from where the input is coming is:

<!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=ISO-8859-1">
    </head>
    <body>
        <form action="InsertImage" name="form1">
            INSERT IMAGE
            <input type="file" name="image"></input>
            <input type="submit" name="upload"></input>
        </form>
    </body>
</html>

When I try to run this code from the HTML page, whatever picture input I give, it always throws FileNotFoundException. I can't understand why I am getting this. The stacktrace is:

java.io.FileNotFoundException: Counter-Strike-Servers.jpg (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at InsertImage.doGet(InsertImage.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:179)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:241)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:580)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)

I tried to print the URL in the servlet and got only shocked.jpg and not the full filepath. Maybe the full filepath is not coming and that is the cause of not finding the file error. So how can I send the full filepath?


Solution

  • While uploading a file from JSP/HTML, you must have the form method set to POST with encType set to multipart/form-data. (HTTP specification)

    <form action="InsertImage" method="post" encType="multipart/form-data" name="form1">
    

    Implement the doPost method to get the same file. You may want to take a look at Apache Commons FileUpload to upload files and Stack Overflow post How to upload files to server using JSP/Servlet? for further details.

    I tried one way to upload the file without using the Apache Common FileUpload and it's working.

    HTML:

    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        </head>
        <body>
            <form action="InsertImage" name="form1" method="post" enctype="multipart/form-data">
                INSERT IMAGE
                <input type="file" name="image"></input>
                <input type="submit" name="upload"></input>
            </form>
    
            </body>
            </html>
    
        </body>
    </html>
    

    Servlet doPost:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url=request.getParameter("image");
        InputStream is = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        PrintWriter pw=response.getWriter();
        pw.println("Reading file");
        while ((line = reader.readLine()) != null) {
             pw.println(line);
        }
        pw.flush();
    }
    

    Now you have to parse the file contents as per your needs. Refer blog post Upload and store files. However, I would strongly suggest using Apache Commons FileUpload for the same.