• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 391
  • Last Modified:

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]
0
domoaarongato
Asked:
domoaarongato
  • 21
  • 20
1 Solution
 
suprapto45Commented:
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
0
 
suprapto45Commented:
>>"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
0
 
suprapto45Commented:
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
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
domoaarongatoAuthor Commented:
I thought                

String img = "img" + count++;

defined it?  No?
0
 
domoaarongatoAuthor Commented:
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?
0
 
suprapto45Commented:
>>"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.
0
 
suprapto45Commented:
>>"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".
0
 
domoaarongatoAuthor Commented:
ooh.  how can i may that String name loop through each time like the value doesn?  can i ++ a String name?
0
 
domoaarongatoAuthor Commented:
wait. i just noticed something.  this servlet wont compile also because img1-img10 only exist when the servlet is executed.
0
 
suprapto45Commented:
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) {

}
0
 
domoaarongatoAuthor Commented:
is there a way to make the prep.setString an array too?
0
 
suprapto45Commented:
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
0
 
domoaarongatoAuthor Commented:
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
0
 
suprapto45Commented:
You have not added count++. Now, your count is always 0.

Additionally, what is the compile error now?
0
 
domoaarongatoAuthor Commented:
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
0
 
suprapto45Commented:
One question to you.

Have you defined your variable with the name "count"?
0
 
domoaarongatoAuthor Commented:
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.
0
 
domoaarongatoAuthor Commented:
Does upload, i mean.  not does not.  

can i edit posts in here?
0
 
suprapto45Commented:
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
0
 
domoaarongatoAuthor Commented:
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.
0
 
suprapto45Commented:
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
0
 
domoaarongatoAuthor Commented:
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).  
0
 
suprapto45Commented:
ok, just get back to me when you are ready.

David
0
 
domoaarongatoAuthor Commented:
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.
0
 
suprapto45Commented:
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?
0
 
domoaarongatoAuthor Commented:
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
0
 
suprapto45Commented:
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
0
 
domoaarongatoAuthor Commented:
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
0
 
domoaarongatoAuthor Commented:
I think i have the static values working now.

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

Static works, dynamic doesnt.
0
 
suprapto45Commented:
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?
0
 
domoaarongatoAuthor Commented:
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) {}
    }
  }
}


0
 
suprapto45Commented:
There are some basic mistakes here.

            // should be outside of loop
            int count = 0;

            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>");
 
                        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
                        count++;
                    }
                    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
                }                                            
            }// end while

            // outside of while
            insert(img);  
0
 
domoaarongatoAuthor Commented:
works now.   was it just the int count = 0 and insert(img); that were wrong?  
0
 
suprapto45Commented:
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
0
 
suprapto45Commented:
Please ask any other questions soon as I am also leaving soon :)
0
 
domoaarongatoAuthor Commented:
thats all for now. :)

are you the only one here who answers questions related to Java?
0
 
suprapto45Commented:
>>"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
0
 
domoaarongatoAuthor Commented:
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?
0
 
suprapto45Commented:
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...
0
 
suprapto45Commented:
String b = a.trim().substring(0, a.length() - 1);
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 21
  • 20
Tackle projects and never again get stuck behind a technical roadblock.
Join Now