1

I am trying insert multiple images to DB.I am inserting images like match the following type

Mytable :

  `Sno` int(11) NOT NULL AUTO_INCREMENT,
  `Class` varchar(45) DEFAULT NULL,
  `Subject` varchar(45) DEFAULT NULL,
  `CreatedBy` varchar(45) DEFAULT NULL,
  `QimgName` varchar(45) DEFAULT NULL,
  `Qimg` mediumblob,
  `AimgName` varchar(45) DEFAULT NULL,
  `Aimg` mediumblob,
  PRIMARY KEY (`Sno`)

MyJsp.jsp

<form action="MatchImgTImgUpload" method="post" enctype="multipart/form-data">
<div id="container" >
 <div>
  <img alt="Image1" id="Image1" src="" width="130px" height="90px"><br><br>
  <img alt="Image2" id="Image2" src="" width="130px" height="90px"><br><br>
  <img alt="Image3" id="Image3" src="" width="130px" height="90px"><br><br> 
  <img alt="Image4" id="Image4" src="" width="130px" height="90px"><br><br>
  <img alt="Image5" id="Image5" src="" width="130px" height="90px"><br><br>
  </div>

  <div>
  <img alt="Image6" id="Image6" src="" width="130px" height="90px"><br><br>
  <img alt="Image7" id="Image7" src="" width="130px" height="90px"><br><br>
  <img alt="Image8" id="Image8" src="" width="130px" height="90px"><br><br> 
  <img alt="Image9" id="Image9" src="" width="130px" height="90px"><br><br>
  <img alt="Image10" id="Image10" src="" width="130px" height="90px"><br><br>
  </div>

</div>
<input type="file"  id="files1" name="files1[]" value="Upload Questions" multiple>
<input type="file"  id="files2" name="files2[]" value="Upload Answers" multiple>
<input type="submit" value="AddToDB?">
</form>

MatchImgTImgUpload.java :

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String clas="I",subject="EVS",uid="112";
        Connection con = null;
        List<String> listGet = new ArrayList<String>();
        List<String> listGet2 = new ArrayList<String>();

        System.out.println("Entered successfully:");
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload fileUpload = new ServletFileUpload(factory);
        List items = null;
        //System.out.println("if0 successfully:");
         Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
         //System.out.println("if0 successfully:");
        if (ServletFileUpload.isMultipartContent(request)) {
            //System.out.println("if0 successfully:");
            // get the request content and iterate through

            try {
                items = fileUpload.parseRequest(request);
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("selected images :"+items);
            if (items != null) {
                //System.out.println("if0 successfully:");
                final Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    //System.out.println("while successfully:");
                    final FileItem item = (FileItem) iter.next();
                    // this is for non-file fields
                    if (item.isFormField()) {
                        //System.out.println("if1 successfully:");

                    // logic for setting non-file fields
                    } else {
                        // item.getName() - gives file name
                        fileMap.put(item.getName(), item.getInputStream());
                        System.out.println("else successfully:"+item.getName());
                        System.out.println("else successfully:"+item.getInputStream());
                        listGet.add(item.getName());

                        String val = item.getInputStream().toString();
                        listGet2.add(val);

                    }
                }
            }
        }
        else
        {
             System.out.println("else successfully:");
        }

        try {
            //System.out.println("try successfully:");

        try {



        Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       

        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");


        Set<String> keySet = fileMap.keySet();
        int listgetcount = 0;
        int count2 =5;
        for (int k=1;k<=5;k++) {
            System.out.println("for successfully:");
        String sql ="INSERT INTO tbl_MatchImgToImg (Class, Subject, CreatedBy, QimgName, Qimg, AimgName, Aimg) values (?, ?, ?, ?, ?, ?, ?)" ; 
        PreparedStatement statement;

            statement = con.prepareStatement(sql);

             statement.setString(1, clas);  
             statement.setString(2, subject);
             statement.setString(3, uid); 

             statement.setString(4, listGet.get(listgetcount));    


             String getval = listGet2.get(listgetcount);

             statement.setBlob(5, fileMap.get(getval));



             statement.setString(6, listGet.get(count2));    

             String getval2 = listGet2.get(count2);
             statement.setBlob(7, fileMap.get(getval2));


            int row = statement.executeUpdate();

            System.out.println("inserted successfully:");
            listgetcount = listgetcount+1;
            count2=count2+1;
        }
        listgetcount=0;
        }
         catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("errror is:"+e);
        }  
         finally{
             try {

                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         }


    }

Its inserting like below,

enter image description here

what i am trying is, there is 10(left side images 5 and right side images 5) images but i have to insert like 1st image(left) is question and 6th(right) image is answer for 1st image like wise want to insert upto 5th image is question and 10th images is answer for 5th image.From the above code everything inserting fine except that statement.setBlob(5, fileMap.get(getval)); and statement.setBlob(7, fileMap.get(getval2)); because its values getting null values.

I guess the issue because of that converting String val = item.getInputStream().toString();listGet2.add(val); so someone please help me out.

Even i tried this,

statement.setBlob(5, fileMap.get(0)); statement.setBlob(7, fileMap.get(5));

But no use.i hope someone will point my mistakes.

Updated :

Here i Updated my question depends on Below posted answer.I tried your code even i have stuck in code,

private DataSource dataSource;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String clas="I",subject="EVS",uid="112";

        List<String> listGet = new ArrayList<String>();

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new RuntimeException("..."); // ...or return a HTTP 400
        }

        // Collecting what's in the request
        Map<String, byte[]> contents = new HashMap<String, byte[]>();
        List<FileItem> items = fileUpload.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                contents.put(item.getFieldName(), item.get());
                listGet.add(item.getFieldName());
            }
        }

        try (Connection connection = ((Statement) dataSource).getConnection()) {
            try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO tbl_MatchImgToImg (Class, Subject, CreatedBy, QimgName, Qimg, AimgName, Aimg) values (?, ?, ?, ?, ?, ?, ?)")) {
                // For this part, you'll need Google Guava - but you can write your own checkNotNull(), too
               int answerimgcount = 5;
                for(int k=0;k<=4;k++){
                byte[] image1 = Preconditions.checkNotNull(contents.get("field1"),
                        "...error: invalid request, missing field1...");
                byte[] image2 = Preconditions.checkNotNull(contents.get("field2"),
                        "...error: invalid request, missing field2...");
                // ...
                stmt.setString(1, clas);    
                stmt.setString(2, subject);
                stmt.setString(3, uid); 

                stmt.setString(4, listGet.get(k));
                // ...
                stmt.setBytes(5, image1);
                // ...
                stmt.setString(6, listGet.get(answerimgcount));
                stmt.setBytes(7, image2);

                answerimgcount =answerimgcount+1;
               }
            }
        }
}

It shows error like below images,

enter image description here

Whatever i give fix the above code not working so tell me where i am wrong now!.

Even i tried simply ,

List<String> listGet = new ArrayList<String>();

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new RuntimeException("..."); // ...or return a HTTP 400
        }

        // Collecting what's in the request
        Map<String, byte[]> contents = new HashMap<String, byte[]>();
        List<FileItem> items = null;
        try {
            items = fileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for (FileItem item : items) {
            if (!item.isFormField()) {
                contents.put(item.getName(), item.get());
                listGet.add(item.getName());
            }
        }

            int answerimgcount = 5;
                for(int k=0;k<=4;k++){
                System.out.println("imageName successfully:"+listGet.get(k));
                byte[] image1 = contents.get("field1");
                System.out.println("image1 successfully:"+image1);
                System.out.println("imageName successfully:"+listGet.get(answerimgcount));
                byte[] image2 =contents.get("field2");
                System.out.println("image1 successfully:"+image2);          


                answerimgcount =answerimgcount+1;
               }

But the OP :

imageName successfully:image1.jpg
image1 successfully:null
imageName successfully:image6.jpg
image1 successfully:null
imageName successfully:image2.jpg
image1 successfully:null
imageName successfully:image7.jpg
image1 successfully:null
imageName successfully:image3.jpg
image1 successfully:null
imageName successfully:image8.jpg
image1 successfully:null
imageName successfully:image4.jpg
image1 successfully:null
imageName successfully:image9.jpg
image1 successfully:null
imageName successfully:image5.jpg
image1 successfully:null
imageName successfully:image10.jpg
image1 successfully:null
imageName successfully:
image1 successfully:null
MMMMS
  • 2,179
  • 9
  • 43
  • 83
  • It read the question for nearly 5min, still didn't manage to understand what you are trying to do. maybe try to modify it to make it easier to understand? – nafas Jan 28 '15 at 11:28
  • @nafas check my question now hope you understand – MMMMS Jan 28 '15 at 11:45
  • instead of adding blob to database, why don't use just add a string location and use the string location to get the data. something like this. that hopefully get rid of NPE – nafas Jan 28 '15 at 12:43

2 Answers2

2

I think that the item being null is the least of your problems (and is actually just a side-effect of your code being overcomplicated and messy - sorry to say this).

The problems in particular:

  • Using a lot of unnecessary data structures (lists and maps)
  • Making lots of assumptions on the contents of those lists
  • Not checking for nulls when you should be
  • Checking for nulls when it's unnecessary (parseRequest() never returns null if you dig into it)
  • InputStream.toString() is just wrong... it's a byte stream, you should NOT just convert it to a Unicode string (especially because you're storing them as blobs in the DB, too)
  • Shouldn't catch and ignore erors which make it impossible to continue processing (FileUploadException)
  • Using System.out rather than a logging framework
  • The finally() would fail with a NPE if you can't get a connection - best to user Java7's try-with block if you can, or Apache Commons' IOUtils.closeQuietly()
  • Working with InputStreams needs a lot of attention, because they can be read only once. I'd suggest to grab the data as a byte[] instead (the DB driver would probably do that anyway).

Now, let's clean it up a little:

// This one SHOULD be dependency injected... opening DB connections on your own
// rather than relying on a connection pool will lead to all sorts of problems
private DataSource dataSource;

protected void doPost2(HttpServletRequest request, HttpServletResponse response) throws ServletException,
        IOException, SQLException, FileUploadException {

    // I'd rather get these dependency-injected
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload fileUpload = new ServletFileUpload(factory);

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new RuntimeException("..."); // ...or return a HTTP 400
    }

    // Collecting what's in the request
    Map<String, byte[]> contents = new HashMap<>();
    List<FileItem> items = fileUpload.parseRequest(request);
    for (FileItem item : items) {
        if (!item.isFormField()) {
            contents.put(item.getFieldName(), item.get());
        }
    }

    try (Connection connection = dataSource.getConnection()) {
        try (PreparedStatement stmt = connection.prepareStatement("...insert sql here...")) {
            // For this part, you'll need Google Guava - but you can write your own checkNotNull(), too
            byte[] image1 = Preconditions.checkNotNull(contents.get("field1"),
                    "...error: invalid request, missing field1...");
            byte[] image2 = Preconditions.checkNotNull(contents.get("field2"),
                    "...error: invalid request, missing field2...");
            // ...

            stmt.setString(1, "...");
            // ...
            stmt.setBytes(4, image1);
            // ...
            stmt.setString(6, "...");
            stmt.setBytes(7, image2);
        }
    }
}
Gergely
  • 365
  • 2
  • 7
  • Thank s for your reply.Check my updated question and answer me where i am wrong? – MMMMS Jan 29 '15 at 05:10
  • @manivasagam, I don't have all the details to give you a solution that you can just copy-paste, and it doesn't make much sense either. So I need you to think a little! `contents.get("field2")` was just an example, as I didn't know how you call your fields. Based on your updates, I suspect you'd want to do something like `contents.get("image2.jpg")` instead. – Gergely Jan 29 '15 at 22:35
  • Also forget about those Lists, you can very easily print the contents map with `System.out.println("Contents map: " + contents)`, or if you just want to see the keys in it then: `System.out.println("Content keys: " + contents.keySet())`. – Gergely Jan 29 '15 at 22:37
1

Finally i found the solution by go through this How get value from LinkedHashMap based on index not on key?. Here is my updated Answer,

try {
            //System.out.println("try successfully:");

        try {



        Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       

        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");


        //Set<String> keySet = fileMap.keySet();
        //Set<String> fileName = keySet;
        int listgetcount = 0;
        int count2 =5;
        for (int k=0;k<5;k++) {
            System.out.println("for successfully:");
        String sql ="INSERT INTO tbl_MatchImgToImg (Class, Subject, CreatedBy, QimgName, Qimg, AimgName, Aimg) values (?, ?, ?, ?, ?, ?, ?)" ; 
        PreparedStatement statement;

            statement = con.prepareStatement(sql);

             statement.setString(1, clas);      
             statement.setString(2, subject);
             statement.setString(3, uid); 
             System.out.println("Qimg name is:"+listGet.get(listgetcount));
             statement.setString(4, listGet.get(listgetcount));    

             System.out.println("Qimg is:"+fileMap.values().toArray()[listgetcount]);
             Object bb = fileMap.values().toArray()[listgetcount];
            // System.out.println("Qimg is:"+listGet2.get(listgetcount));

            // System.out.println("finallyyyy:"+fileMap.get("files1"));
             statement.setBinaryStream(5, (InputStream) bb);


             System.out.println("Aimg name is:"+listGet.get(count2));
             statement.setString(6, listGet.get(count2));    

             System.out.println("Aimg is:"+fileMap.values().toArray()[count2]);
             Object bb2 = fileMap.values().toArray()[count2];
             //System.out.println("Qimg is:"+fileMap.get("files2"));
             //String getval2 = listGet2.get(count2);
             statement.setBinaryStream(7, (InputStream) bb2);


            int row = statement.executeUpdate();

            System.out.println("inserted successfully:");
            listgetcount = listgetcount+1;
            count2=count2+1;
        }
        listgetcount=0;
        }
Community
  • 1
  • 1
MMMMS
  • 2,179
  • 9
  • 43
  • 83