Tuesday, 2 July 2013

Upload Image With AJAX In Spring MVC

Here i have uploaded image to database using spring mvc and hibernate.

you need to create Photo column in Model.

Modal

@Entity
@Table(name="person_information")
public class Person implements Serializable {

@Column(name="Photo")
@Lob
private byte[] photo; 

public byte[] getPhoto() {
        return photo;
    }

public void setPhoto(byte[] photo) {
        this.photo = photo;
    }

Ajax Function Call On any Html Element

call ajax function on click event of upload button.

<input type="button" Value="Upload" onclick="performAjaxSubmit()" />
function performAjaxSubmit() {
var id = $("#pid").val();
var photoFile= document.getElementById("photo").files[0];
var formdata = new FormData();
formdata.append("sampleFile", photoFile);
formdata.append("id", id);
var xhr = new XMLHttpRequest();
xhr.open("POST", url + "/person/UploadPhoto", true);
xhr.send(formdata);
xhr.onload = function(e) {
if (this.status == 200) {
             alert("Photo Successfully uploaded")
}
};
}

Controller Mehtod for Upload

this method is in class and this class is having @RequestMapping('/client/')
u need to include some dependancies in pom file because i have used image scaler  plugins   

@RequestMapping(method = RequestMethod.POST, value = "UploadPhoto")
public void uploadPersonPhoto(HttpServletRequest request,
HttpServletResponse response)                                                                                                              throws FileUploadException,IOException
{
File uploadedFile = null;
String ajaxUpdateResult = "";
int id = 0;
String fileName = "";
Person p = null;
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
 for (FileItem item1 : items) //for starts
 {
if (item1.isFormField())
     {
id = Integer.parseInt(item1.getString());
p = personService.getPersonInformation(id);
 
      } else
     {
Iterator iterator = items.iterator();
 
       while (iterator.hasNext())  //while starts
       {
FileItem item = (FileItem) iterator.next();
              if (!item.isFormField())
              {
fileName = item.getName();
String root = "src/main/webapp/resources/upload/";
File path = new File(root + "/fileuploads");
 
if (!path.exists()) {
path.mkdirs();
}
uploadedFile = new File(path + "/" + fileName);
 
             try {
item.write(uploadedFile);                   ////The File Willbe Uploaded at above given path                                                                                          /////       src/main/webpage/resources/upload/
} catch (Exception e) {
}
ajaxUpdateResult = fileName + " is Uploaded Successfully" ;
}
}  //while End
} 
} //for loop end
 BufferedImage bi = new BufferedImage(150, 150,BufferedImage.TYPE_BYTE_BINARY);
 
bi = ImageIO.read(uploadedFile);
BufferedImage bio = Scalr.resize(bi, 150);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bio, "jpg", baos);
byte[] bFile = baos.toByteArray();

          p.setPhoto(bFile);      ///////this will upload file in database in byte format
 
          response.getWriter().print(ajaxUpdateResult);
}