Solved

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

Posted on 2006-11-13
41
344 Views
Last Modified: 2010-03-31
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
Comment
Question by:domoaarongato
  • 21
  • 20
41 Comments
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936204
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936220
>>"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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936237
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
 

Author Comment

by:domoaarongato
ID: 17936282
I thought                

String img = "img" + count++;

defined it?  No?
0
 

Author Comment

by:domoaarongato
ID: 17936287
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936332
>>"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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936334
>>"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
 

Author Comment

by:domoaarongato
ID: 17936354
ooh.  how can i may that String name loop through each time like the value doesn?  can i ++ a String name?
0
 

Author Comment

by:domoaarongato
ID: 17936376
wait. i just noticed something.  this servlet wont compile also because img1-img10 only exist when the servlet is executed.
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936381
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
 

Author Comment

by:domoaarongato
ID: 17936397
is there a way to make the prep.setString an array too?
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936413
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
 

Author Comment

by:domoaarongato
ID: 17936434
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936445
You have not added count++. Now, your count is always 0.

Additionally, what is the compile error now?
0
 

Author Comment

by:domoaarongato
ID: 17936452
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936473
One question to you.

Have you defined your variable with the name "count"?
0
 

Author Comment

by:domoaarongato
ID: 17936520
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
 

Author Comment

by:domoaarongato
ID: 17936522
Does upload, i mean.  not does not.  

can i edit posts in here?
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936536
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
 

Author Comment

by:domoaarongato
ID: 17936556
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 16

Expert Comment

by:suprapto45
ID: 17936568
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
 

Author Comment

by:domoaarongato
ID: 17936614
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936617
ok, just get back to me when you are ready.

David
0
 

Author Comment

by:domoaarongato
ID: 17936623
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17936713
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
 

Author Comment

by:domoaarongato
ID: 17939135
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17943340
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
 

Author Comment

by:domoaarongato
ID: 17943926
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
 

Author Comment

by:domoaarongato
ID: 17943987
I think i have the static values working now.

However, the static values enter 3 times if there were 3 files uploaded.
0
 

Author Comment

by:domoaarongato
ID: 17944046
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17944361
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
 

Author Comment

by:domoaarongato
ID: 17949071
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
 
LVL 16

Accepted Solution

by:
suprapto45 earned 500 total points
ID: 17953139
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
 

Author Comment

by:domoaarongato
ID: 17953241
works now.   was it just the int count = 0 and insert(img); that were wrong?  
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17953263
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17953329
Please ask any other questions soon as I am also leaving soon :)
0
 

Author Comment

by:domoaarongato
ID: 17953390
thats all for now. :)

are you the only one here who answers questions related to Java?
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17953414
>>"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
 

Author Comment

by:domoaarongato
ID: 17953426
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17953451
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17953456
String b = a.trim().substring(0, a.length() - 1);
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
The viewer will learn how to implement Singleton Design Pattern in Java.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now