0

I am trying to upload an image in mysql database using hibernate and spring ajax call is done in createImge.jsp page and controller is provided to handle the request where the image absolute path is stored in a variable and passed the entire entity object to daoImpl class where hibernate program is used to store in the database.

I did not get any error but the thing is it is not inserted into the database and received alert not inserted from ajax with no errors even on console.

Kindly provide any solution for this.

CreateImge.jsp

       <html>
       <body>
       <form class="form-horizontal bucket-form" id="myform" method="post" >
               <div class="control-label text-center">
               <p class="required"><em>required fields</em></p></div>

                <div class="form-group"> 
                    <label class="col-sm-3 control-label">ID</label>
                    <div class="col-sm-6">
                        <input type="number" class="form-control" id="id" >
                    </div>
                    </div>


                <div class="form-group"> 
                    <label class="col-sm-3 control-label">Upload 
                  image</label>
                    <div class="col-sm-6">
                        <input type="file" class="form-control" id="path" 
             accept="image/*">
                    </div>
                </div>                  

                <div class="form-group">
                    <div class="col-lg-offset-3 col-lg-6">
                        <button class="btn btn-primary" id="speakerSubmit" 
               type="submit">Save</button>
                        <button type="reset" class="btn btn" 
              onClick="myFunction()">Reset</button>
                        <script type="text/javascript">
                            function myFunction() {
                            document.getElementById("myform").reset();
                            }
                        </script>
                    </div>
                </div>

            </form>

         <script src="js/jquery2.0.3.min.js"></script>
         <script 
   src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
   </script>
   <script src="js/bootstrap.js"></script><!--bootstrap script-->
   <script src="js/jquery.dcjqaccordion.2.7.js"></script><!--accordion 
   script-->
  <script src="js/scripts.js"></script><!--accordion script-->
   <script src="js/jquery.nicescroll.js"></script><!--toggle_effect script-->

  <script>
  $( document ).ready(function() {
  $("#speakerSubmit").click(function(event){
  event.preventDefault();
   alert("create ready");
   var id=document.getElementById("id").value;
   var path=document.getElementById("path").value;
   alert(path);
 var details={id:id,path:path};
 alert(details.id+" "+details.path);
 var res=JSON.stringify(details);
 alert("mytxt "+res);

  $.ajax({ 
    url: "http://localhost:8080/EMS_APP/imgadd",
    type: "POST",
    contentType:"application/json",
    data : res,
    success: function(data, status) {
        if(data){

            alert("inserted");

        }else{
        //window.open("index.jsp","_self");
            alert("not inserted");
        }
    },
     error: function(e) { 
        console.log("error");
    }  
  });
  });
  });
 </script>
 </body>
 </html>

Pojo class

package com.ems.DO;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="forimgs")
public class ImgeClass {

@Id
@Column(name="id")
private int id;

@Column(name="path")
private String path;
public String getPath() {
    return path;
}

public void setPath(String path) {
    this.path = path;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@Column(name="imgstore")
 private byte[] image;

public byte[] getImage() {
    return image;
}

public void setImage(byte[] image) {
    this.image = image;
}
}

Controller Class method

  @RequestMapping(value="/imgadd",method=RequestMethod.POST)
  public @ResponseBody void addimage (@RequestBody ImgeClass e){
    System.out.println(e.getPath());
    speakerService.addImg(e);
}

ServiceImpl Class method

    @Override
    public void addImg(ImgeClass e) {
    System.out.println("in service");
    speakerDao.addImage(e);
    }

DaoImpl Class method

   public void addImage(ImgeClass e)
    {

    System.out.println("in dao");
    System.out.println(e.getId());
    System.out.println(e.getPath());
    String path=e.getPath();
    File file=new File(path);
    System.out.println("Your file length is "+file.length());
    byte[] bfile=new byte[(int) file.length()];
    try {

     FileInputStream fileInputStream =new FileInputStream(file);

     fileInputStream.read(bfile);
     fileInputStream.close();
     for(byte b : bfile) {     //Just to check whether bfile has any content
         System.out.print(b +" ");
     }
     }
    catch(Exception ex) {
    ex.printStackTrace();
   }
   e.setImage(bfile);
    Session session = sessionFactory.getSessionFactory().openSession();
    System.out.println(e.getId()+" "+e.getPath()+" "+e.getImage());

     session.persist(e);
    //System.out.println("value");
    System.out.println("One image uploaded into database");
     }

Image for Output in the console

Empty table in forImgs

Ramana
  • 31
  • 1
  • 7
  • 1
    you can't upload an image as text (including text within JSON), unless you base-64 encode it. You need to do a multipart upload. You can google dozens of examples of doing that via ajax. The fact you've called the relevant variable "path" suggests a fundamental misunderstanding of the process - you don't send the server a file path (the "path" is a path the user's machine and is therefore totally useless to the server, which can't access that path), you send it the _file content_ as an array of bytes. The server then stores this wherever it needs to (maybe on disk or in a database,for example) – ADyson Nov 23 '17 at 15:51
  • @ADyson Thank you for the comment,please provide a link for reference. – Ramana Nov 24 '17 at 05:09
  • As I have [commented](https://stackoverflow.com/questions/47449653/passing-image-to-controller-class-in-json-format-in-spring-mvc) on your original question, and as @ADyson, pointed out — you can use [base64](https://en.wikipedia.org/wiki/Base64), to store images as a text in DB or send them inside JSON. Again, in comment to your original post, I've provided link to the [answer which addresses usage of base64 in Java] (https://stackoverflow.com/a/13109632/8554766). Nothing new to add, really =) –  Nov 24 '17 at 09:38
  • @Ramana like I said in the first comment: https://www.google.co.uk/search?q=ajax+file+upload&oq=Ajax+file+upload&aqs=chrome.0.0j69i60l2j0l3.2479j0j7&sourceid=chrome&ie=UTF-8 – ADyson Nov 24 '17 at 09:54

0 Answers0