FileNotFoundException uploading an image to Oracle database

2.4k views Asked by At

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?

2

There are 2 answers

0
Sandeep Pathak On BEST ANSWER

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.

4
Humungus On

It looks like a local error in the sense that it really can't find the file specified by url. I would suggest debugging by printing out the url String and creating a dummy class to feed the doGet method a handmade request/response to make sure whether the problem is in the program itself or in some unexpected passing/formating of the request (you might want to comment out some parts of the method for this, e.g. the connection and statement part).

EDIT: Example of the dummy class (or method, in this case):

private void testDoGet() {
    // I would suggest commenting out all the Connection and PreparedStatement
    // parts of the doGet method so you don't have to establish the connection.
    // - this is just to test if you can get to the image on your machine.
    HttpServletRequest request;
    //insert into request the image parameter with the string to the requested image
    HttpServletResponse response //TODO initialize with some class implementing it
    doGet(request, response);
    // if you want to, set a breakpoint somewhere here to check 
    // what's in the classes now        
}