Link to home
Start Free TrialLog in
Avatar of Lucky48390
Lucky48390

asked on

Cannot upload file

Hey experts,

I have a servlet that should allow my users to upload files to be stored in the database using a standard multipart form. I'm pretty sure that I haven't missed anything, but I am still receiving File Not Found error. Can someone take a look and let me know if they see anything that might be the cause of the File Not Found error that I am receiving?

BTW: I suppose I should tell you that this works on my standalone test environment perfectly, but not on the server.

Thank you!

          OutputStream fileOut = null;
          FileInputStream fileIn = null;
          File binaryFile = new File(addFiles[fileCt]);  //addFiles comes directly from the multipart form
          fileIn = new FileInputStream(binaryFile);
          fileOut = blobLocator.getBinaryOutputStream();
          byte[] buffer = new byte[blobLocator.getBufferSize()];
          int length = 0;
          while((length = fileIn.read(buffer)) != -1)
          {
            fileOut.write(buffer, 0, length);
          }
          fileOut.close();
          fileOut = null;      
          fileIn.close();
          fileIn = null;
Avatar of petmagdy
petmagdy
Flag of Canada image

hi lucky ur input is incomplete, we need ur Servlet complete function (the whole service(), or doGet() or doPost(), also what library u use for upload (give us the imports of ur servlet) also please mention the Servlet engine u use and the OS
Avatar of Lucky48390
Lucky48390

ASKER

hi petmagdy - i use OC4J and i believe it's on linux redhad

here are my imports:
import prospectTracking.ProspectsCommon;
import java.io.*;
import java.text.*;
import java.sql.*;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
import oracle.jdbc.OracleResultSet;
import oracle.jdbc.pool.OracleDataSource;
import oracle.sql.CLOB;
import oracle.sql.BLOB;

Here is my whole doPost() -it isn't pretty, but...:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    ProspectsCommon pc = new ProspectsCommon();
    response.setContentType(CONTENT_TYPE);

    HttpSession session = request.getSession(true);
   
    Connection conn = null;    
    Statement stmt = null;
    ResultSet rset = null;
   
    BLOB blobLocator = null;
   
    PrintWriter out = response.getWriter();
   
    String[] addFiles = request.getParameter("HFileList").split(", ");

    long blobId = 0;    
    long idVal = 0;
    long orgId = 0;

    try
    {
      conn = pc.dbConnect();
      //set database connection
     
      stmt = conn.createStatement();
      //create a statement object

      idVal = Long.valueOf(request.getParameter("p_id").toString()).longValue();
      //get the next value from the IRGIS_SALES_PROSPECTS_S sequence
     
      for(int fileCt = 0; fileCt < addFiles.length; fileCt++)
      {
        String[] fileName = addFiles[fileCt].split("\\\\");
       
        if(fileName.length > 1)
        //only if a full file path is available
        {
          blobId = pc.getNextSequenceVal("IRGIS_ATTACHMENTS_S", conn);
          //get the next value from the IRGIS_TEXT_COLLECTION_S sequence
     
          ServletContext sc = getServletContext();
          String mimeType = sc.getMimeType(addFiles[fileCt]);
         
          stmt.executeUpdate(createEmptyBlob(request, idVal, blobId, java.net.URLEncoder.encode(fileName[fileName.length - 1],"UTF-8"),mimeType,lngPerson));
          rset = stmt.executeQuery(getBlobLocator(request, idVal, blobId));
          rset.next();
          blobLocator = ((OracleResultSet)rset).getBLOB(1);
          rset.close();
          rset = null;
       
          OutputStream fileOut = null;
          FileInputStream fileIn = null;
          File binaryFile = new File(addFiles[fileCt]);
          fileIn = new FileInputStream(binaryFile);
          fileOut = blobLocator.getBinaryOutputStream();
          byte[] buffer = new byte[blobLocator.getBufferSize()];
          int length = 0;
          while((length = fileIn.read(buffer)) != -1)
          {
            fileOut.write(buffer, 0, length);
          }
          fileOut.close();
          fileOut = null;      
          fileIn.close();
          fileIn = null;
        }
        conn.commit();
        //commit the changes to the database
      }
     
      stmt.close();
      conn.close();
   
      out.println("<html>");
      out.println("<head><title>Update Prospect</title></head>");
      out.println("<body onLoad='opener.location.reload(true);window.close()'>");
      out.println("</body></html>");
      out.close();
    }
   
    catch(SQLException ex)
    {
      try{
      if ( conn != null ){ conn.rollback() ; }
      //if the connection still exists, roll it back
      } catch(SQLException e){}
      System.out.println("SQLException caught");
     
      System.out.println("---");
      while ( ex != null )
      {
          System.out.println("Message   : " + ex.getMessage());
          System.out.println("SQLState  : " + ex.getSQLState());
          System.out.println("ErrorCode : " + ex.getErrorCode());
          System.out.println("Local Message : " + ex.getLocalizedMessage());
          System.out.println("---");
          ex = ex.getNextException();
      }
    }
   
    catch(ParseException pe){}
  }

thank you for your help!
ASKER CERTIFIED SOLUTION
Avatar of petmagdy
petmagdy
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Lucky,

There is a big probability that the client try to upload "c:/java.txt" in their local harddrive but your program will actually try to search that particular file in the server local harddrive that causes FileNotFound Exception. How to solve it? well, you must use FileUpload tags to help you. FileUpload get the content of the Files and send it to your servlet instead of sending the paths and the name of the file.

The link is the one that petmagdy gave - (http://jakarta.apache.org/commons/fileupload/)

Please do not hesitate to ask again.

Dave
Thank you for all of the good advice.

I worded my question inappropriately, I apologize. I do not want to upload the file. I want to copy the contents of the file into a blob field.

I really liked the file upload utility from apache commons, but the problem is that I cannot upload or copy directly from the multi-part form in my project. At the time of file selection, I do not have the required foreign key yet, and if at all possible, i would like to avoid storing the file on the server.

Can you guys think of any other suggestions, or is this not possible?

Thanks again!
if u r doing this to store ur file into database, their is a way not using blob but using InputStream, take a look at this:

http://www.ideas2work.com/share-knowledge-details.php/username/guddu/title/Storing%20and%20retrieving%20Files%20to%20and%20from%20Database%20as%20stream./technology/JDBC%20-%20Java/
Thanks for the response! The code in that link is what i'm already doing - except I am not storing in mysql database. The code assumes that the file is already on the server. I do not want to store the file on the server, I want to extract the contents from the users local hard drive.
let me understand this:

u r a web application that want to access browser users harddisk? Please clarify
I'm sorry - I am terrible at explaining... The multi part form I am using opens from an "add attachment" link on my main form. When the user clicks Ok to submit the form - instead of sending it to the database right away I need to wait until the information from the main form is sent.

I know this can be accomplished by uploading to a temp folder on the server when the user submits the multi-part form - I am just trying to avoid that route because I am ignorant to the servers filing system - but it looks like that's the route I'm going to have to take.

Anyways, thanks for your help and the awesome links.