Link to home
Start Free TrialLog in
Avatar of domoaarongato
domoaarongato

asked on

trying to upload files to server and file name to DB. can't compile + streamling.

I have the oreilly upload multifile form and servlet working correctly.  but i cant add the functionality to have the file names upload to the DB.

i return 10 errors, 1 for each string i try and pass to the insert servlet.
[code]
imageUpload.java:62: cannot find symbol
symbol  : variable img10
location: class savedata.imageUpload
                        insert(img1,img2,img3,img4,img5,img6,img7,img8,img9,img10);
                                                                            ^
[/code]

here is my entire code.  why is it not getting the correct string?  im printing out the value and it looks ok??

also, is there a better way to pass all those String names?  I have a form with about 50 feilds.  i can;t image passing 50 Strings through the method like that is good?  

here is the entire code.  I *think* it should work, or at least close to working once i can compile the file.

[code]
package savedata;

import javax.servlet.*;
import javax.servlet.http.*;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;
import com.oreilly.servlet.multipart.FilePart;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;

public class imageUpload extends HttpServlet {
   
    private String fileSavePath;

  public void init(){
      // save uploaded files to a 'data' directory in the web app
      fileSavePath =   getServletContext().getRealPath("/") + "data";
  }
  public void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,
    java.io.IOException {
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>File uploads</title>");  
    out.println("</head>");
    out.println("<body>");
    out.println("<h2>Here is information about any uploaded files</h2>");
    try{
        // file limit size of five megabytes
        MultipartParser parser = new MultipartParser(
           request,5 * 1024 * 1024);
        Part _part = null;
            int count = 1;
        while ((_part = parser.readNextPart()) != null) {
           if (_part.isFile()) {
               // get some info about the file
               FilePart fPart = (FilePart) _part;
               String name = fPart.getFileName();
                     if (name != null) {
               long fileSize = fPart.writeTo(
                 new java.io.File(fileSavePath));
               out.println("The user's file path for the file: " +
                 fPart.getFilePath() + "<br>");
                        String img = "img" + count++;
                        out.print(img);
               out.println("The content type of the file: " +
                 fPart.getContentType()+ "<br>");
               out.println("The file size: " +fileSize+ " bytes<br><br>");
              //commence with another file, if there is one
            } else {
               out.println(
                 "The user did not upload a file for this part.");
            }
          }    else if (_part.isParam()) {
              // do something else if it is a non-file type parameter,
              //such as a user name
          }
                    insert(img1,img2,img3,img4,img5,img6,img7,img8,img9,img10);                  
        }// end while
        out.println("</body>");
        out.println("</html>");
        out.close();

            
    } catch (java.io.IOException ioe){
       //an error-page in the deployment descriptor is
       //mapped to the java.io.IOException
        throw new java.io.IOException(
            "IOException occurred in: " + getClass().getName());
}
    }
    public void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException,
        java.io.IOException {
       
        throw new ServletException(
            "GET method used with " + getClass().getName()+
                 ": POST method required.");
    }
public void insert(String img1,String img2,String img3, String img4,String img5,String img6,String img7, String img8, String img9,String img10) {
    Connection con = null;
     PreparedStatement prep = null;
     String sql = null;
     ResultSet result;
     

    try {
      Class.forName("org.gjt.mm.mysql.Driver").newInstance();
      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/root?user=root&password=");

      if(!con.isClosed())
        System.out.println("Successfully connected to " +
          "MySQL server using TCP/IP...");
           
                       try
           {
          sql = "INSERT INTO form_main(img1,img2,img3,img4,img5,img6.img7,img8,img9,img10)VALUES(?,?,?,?,?,?,?,?,?,?)";          
          prep = con.prepareStatement(sql);
              prep.setString(1, img1);
              prep.setString(2, img2);
              prep.setString(3, img3);
              prep.setString(4, img4);
              prep.setString(5, img5);
              prep.setString(6, img6);
              prep.setString(7, img7);
              prep.setString(8, img8);
              prep.setString(9, img9);
              prep.setString(10,img10);
                        prep.executeUpdate();
          }
          catch(Exception m)
          {
          System.out.print(m.getMessage());
          }

    } catch(Exception e) {
      System.err.println("Exception: " + e.getMessage());
    } finally {
      try {
        if(con != null)
          con.close();
      } catch(SQLException e) {}
    }
  }
}


[/code]
Avatar of suprapto45
suprapto45
Flag of Singapore image

Hi,

There is a *dot* instead of a comma there.

>>"img1,img2,img3,img4,img5,img6.img7,img8,img9,img10"
                                                    ^
should be

img1,img2,img3,img4,img5,img6,img7,img8,img9,img10
>>"I have a form with about 50 feilds.  i can;t image passing 50 Strings through the method like that is good?"
Yeah, you are right. Passing 50 different parameters to the method is not an appropriate way.

What you can do is to create one JavaBean with 50 attributes and you just pass this JavaBean to the method such as

public class MyImage {
    private String img1;
    private String img2;

    public void setImg1(String img1) {
        this.img1 = img1;
    }

    public String getImg1() {
        return this.img1;
    }

    public void setImg2(String img2) {
        this.img2 = img2;
    }

    public String getImg2() {
        return this.img2;
    }
}

So, later on

MyImage mi = new MyImage();
mi.setImg1("whatever1");
mi.setImg2("whatever2");

insert(mi);

then in your declaration

public void insert(MyImage mi) {

}

Hope that helps
David
Then one more thing.

When you execute the code of
insert(img1,img2,img3,img4,img5,img6,img7,img8,img9,img10);

Have you defined img1 - img10? I did not see that in your codes
Avatar of domoaarongato
domoaarongato

ASKER

I thought                

String img = "img" + count++;

defined it?  No?
So, later on

MyImage mi = new MyImage();
mi.setImg1("whatever1");
mi.setImg2("whatever2");

insert(mi);

then in your declaration

public void insert(MyImage mi) {

}


Does that go in the main servlet that is passing the values to the method?
>>"String img = "img" + count++;"
NO.

Let's see the differences.
String img = "img1";
String img1 = "img1";
String img12 = "img12";

You have three different String there named img, img1 and img12.

>>"Does that go in the main servlet that is passing the values to the method?"
Yes. You are correct.
>>"String img = "img" + count++;"
means that you only have one variable called img whose values are replaced by the looping. So in the end, you only have one variable called "img".
ooh.  how can i may that String name loop through each time like the value doesn?  can i ++ a String name?
wait. i just noticed something.  this servlet wont compile also because img1-img10 only exist when the servlet is executed.
Nope, unfortunately.

Well, why don't you use array? As I assumed that this is always be 10, you can create something like

String[] img = new String[10];

later on

int param = 0;
param = count;

img[count] = "img" + ++param;

Then pass it as array to insert.

insert (img);

public void insert(String[] img) {

}
is there a way to make the prep.setString an array too?
Nope, but you can use for..loop to trick it as

for (int i = 0; i < img.length; i++) {
    prep.setString((i + 1), img[i]);
}

David
i dont think i've got param = count; in the right spot. i keep getting compile errors.

String[] img = new String[10];
        while ((_part = parser.readNextPart()) != null) {
       if (_part.isFile()) {
   // get some info about the file
               FilePart fPart = (FilePart) _part;
               String name = fPart.getFileName();
                     if (name != null) {
               long fileSize = fPart.writeTo(
                 new java.io.File(fileSavePath));
               out.println("The user's file path for the file: " +
                 fPart.getFilePath() + "<br>");
                        int param = 0;
                        param = count;  
                        img[count] = "img" + ++param;
               out.println("The content type of the file: " +
                 fPart.getContentType()+ "<br>");
               out.println("The file size: " +fileSize+ " bytes<br><br>");
              //commence with another file, if there is one
You have not added count++. Now, your count is always 0.

Additionally, what is the compile error now?
imageUpload.java:52: cannot find symbol
symbol  : variable count
location: class savedata.imageUpload
                                param = count;
                                        ^
imageUpload.java:53: cannot find symbol
symbol  : variable count
location: class savedata.imageUpload
                                img[count] = "img" + ++param;
                                    ^
2 errors
One question to you.

Have you defined your variable with the name "count"?
I accidentally removed  int count = 1;.   I put it back and now it compiles.   I see a problem though.   if someone does not upload less than 10 files (im testing it with 3 now) the values don't enter into the DB.  IS this because the Query thinks that there are 20 values about to be inserted?   And if this is the problem, how can i fix this to accomidate.


P.S  I've increaseed the points on this.
Does upload, i mean.  not does not.  

can i edit posts in here?
Yes,

I do not want to directly answer you so that you are aware on what's going on and won't repeat the same problem again. That's why we all here :).

>>"I see a problem though.   if someone does not upload less than 10 files (im testing it with 3 now) the values don't enter into the DB."
How if the user uploads more than 10? Are they inserted to DB?

Any exception or error message in your console?

David
I appreciate all the help so far.   Unfortunately it's very late and im losing focus:)

In STDout it says No value specified for parameter 2.  Which is what we thought would happen.  Perhas i can do a condition in the prepared statement that says enter a null value?  this isnt really ideal i don't think.

The user wont upload mroe than 10.  ive set a limit of 10 on it.
Okay,

One thing you can do then.

Just after the
String[] img = new String[10];

for (int j = 0; j < img.length; j++) {
    img[j] = "";
}

This means that all the 10 string will be set to "".

David
ok, im going crazy.  i think i need to sleep:)  whats happening now is it's inserting everything as "img2"  in the "img2" column in the DB.  It should be inserting file names and it should be inserting on a single row (i think we talked about this yesterday, it has to do with where insert() is placed).  
ok, just get back to me when you are ready.

David
ok i fixed the file name problems. with this img[count] = fPart.getFilePath();  I think i may know how to get them to insert into one row but the thing i dont know is why they are all inserting into the img2 column and not columns img1, img2,img3 and so on.
Hi,

          sql = "INSERT INTO form_main(img1,img2,img3,img4,img5,img6.img7,img8,img9,img10)VALUES(?,?,?,?,?,?,?,?,?,?)";          
          prep = con.prepareStatement(sql);

          System.out.println("img.length = " + img.length);
          for (int i = 0; i < img.length; i++) {
                prep.setString((i + 1), img[i]);
          }
              prep.executeUpdate();

What does System.out.println("img.length = " + img.length); print out?
this is what i have
Successfully connected to MySQL server using TCP/IP...
img.length = 10
Column count doesn't match value count at row 1Successfully connected to MySQL server using TCP/IP...
img.length = 10
Column count doesn't match value count at row 1Successfully connected to MySQL server using TCP/IP...
img.length = 10
Column count doesn't match value count at row 1
Hi,

Try to use static (hardcoded) value just for testing.

sql = "INSERT INTO form_main(img1,img2,img3,img4,img5,img6.img7,img8,img9,img10)VALUES(?,?,?,?,?,?,?,?,?,?)";

prep.setString(1, "1");
prep.setString(2, "2");
.
.
prep.setString(10, "10");

and see whether it works or not
I get this error in my stdout

Column count doesn't match value count at row 1Successfully connected to MySQL server using TCP/IP...
Column count doesn't match value count at row 1Successfully connected to MySQL server using TCP/IP...
Column count doesn't match value count at row 1Successfully connected to MySQL server using TCP/IP...
Column count doesn't match value count at row 1
I think i have the static values working now.

However, the static values enter 3 times if there were 3 files uploaded.
I just tried the dynamic way again and it's not working. plus it's still entering into img 2.

Static works, dynamic doesnt.
Okay,

I may not be available very much in EE today. Can you post your latest and current Servlet for me to look later on?
here is my entire file.

package savedata;

import javax.servlet.*;
import javax.servlet.http.*;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;
import com.oreilly.servlet.multipart.FilePart;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;

public class imageUpload extends HttpServlet {
   
    private String fileSavePath;

  public void init(){
      // save uploaded files to a 'data' directory in the web app
      fileSavePath =   getServletContext().getRealPath("/") + "data";
  }
  public void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,
    java.io.IOException {
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>File uploads</title>");  
    out.println("</head>");
    out.println("<body>");
    out.println("<h2>Here is information about any uploaded files</h2>");
    try{
        // file limit size of five megabytes
        MultipartParser parser = new MultipartParser(
           request,5 * 1024 * 1024);
        Part _part = null;
int count = 1;
String[] img = new String[10];
for (int j = 0; j < img.length; j++) {
    img[j] = "";
}

        while ((_part = parser.readNextPart()) != null) {

if (_part.isFile()) {
           
 // get some info about the file
               FilePart fPart = (FilePart) _part;
               String name = fPart.getFileName();
                     if (name != null) {
               long fileSize = fPart.writeTo(
                 new java.io.File(fileSavePath));
               out.println("The user's file path for the file: " +
                 fPart.getFilePath() + "<br>");
                        int param = 0;
                        param = count;  
                        img[count] = fPart.getFilePath();
               out.println("The content type of the file: " +
                 fPart.getContentType()+ "<br>");
               out.println("The file size: " +fileSize+ " bytes<br><br>");
              //commence with another file, if there is one
            } else {
               out.println(
                 "The user did not upload a file for this part.");
            }
          }    else if (_part.isParam()) {
              // do something else if it is a non-file type parameter,
              //such as a user name
          }
                    insert(img);                  
        }// end while
        out.println("</body>");
        out.println("</html>");
        out.close();

            
    } catch (java.io.IOException ioe){
       //an error-page in the deployment descriptor is
       //mapped to the java.io.IOException
        throw new java.io.IOException(
            "IOException occurred in: " + getClass().getName());
}
    }
    public void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException,
        java.io.IOException {
       
        throw new ServletException(
            "GET method used with " + getClass().getName()+
                 ": POST method required.");
    }
public void insert(String[] img) {
    Connection con = null;
     PreparedStatement prep = null;
     String sql = null;
     ResultSet result;
     

    try {
      Class.forName("org.gjt.mm.mysql.Driver").newInstance();
      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxx?user=root&password=");

      if(!con.isClosed())
        System.out.println("Successfully connected to " +
          "MySQL server using TCP/IP...");
           
                       try
           {
         sql = "INSERT INTO form_main(img1,img2,img3,img4,img5,img6,img7,img8,img9,img10)VALUES(?,?,?,?,?,?,?,?,?,?)";          
          prep = con.prepareStatement(sql);

    //      System.out.println("img.length = " + img.length);
         for (int i = 0; i < img.length; i++) {
               prep.setString((i + 1), img[i]);
          }
      //      prep.setString(1, "1");
      //      prep.setString(2, "2");
      //      prep.setString(3, "3");
      //      prep.setString(4, "4");
      //      prep.setString(5, "5");
      //      prep.setString(6, "6");
      //      prep.setString(7, "7");
      //      prep.setString(8, "8");
      //      prep.setString(9, "9");
      //      prep.setString(10, "10");
              prep.executeUpdate();

          }
          catch(Exception m)
          {
          System.out.print(m.getMessage());
          }

    } catch(Exception e) {
      System.err.println("Exception: " + e.getMessage());
    } finally {
      try {
        if(con != null)
          con.close();
      } catch(SQLException e) {}
    }
  }
}


ASKER CERTIFIED SOLUTION
Avatar of suprapto45
suprapto45
Flag of Singapore 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
works now.   was it just the int count = 0 and insert(img); that were wrong?  
Both are wrong.

First, count should be outside the loop otherwise, the count will always be set to zero and you are actually inserting the value to the first element of array again and again.

Then, insert should also be outside the loop. Otherwise, if user upload 3 files, you will end up with 3 insertion while in fact, you only want 1 insertion. So the while loop should only construct the information that we want (in this case, filling the information to array) then once the while loop ended, pass this array to the insert method.

Hope that helps
Please ask any other questions soon as I am also leaving soon :)
thats all for now. :)

are you the only one here who answers questions related to Java?
>>"are you the only one here who answers questions related to Java?"
Nope, there are many genius in Java here. I am just intermediate :).

However, sometimes other experts will leave this question to the expert that has responded before unless the expert is unable to solve it.

David
gotcha ;)

well thanks again.  I'll have many more questions im sure.


I have one last (for now) if you have the time.    Trailing comma's, how do i get rid of them?
Trailing comma,

Should be rather easy. Is it removing the last comma? If so, just trim (remove any trailing space) the string and remove the last character :).

String a = "a,b,c,d,e,";

String b = a.substring(0, a.length() - 1);

Try that...
String b = a.trim().substring(0, a.length() - 1);