Praveen Singh

HTML5 AJAX File upload (Image or HTML5 Canvas data) to Java backend


HTML5 AJAX File upload (Image or HTML5 Canvas data) to Java backend

Step by step tutorial and demo of how you can upload or read an image file from your local file system, display it as image and HTML5 Canvas and upload it to java backend.

This article can also be used a tutorial for new HTML5 api for multipart upload or FormData upload and java7 api for MultipartConfig upload. this article also explained how a HTML5 canvas can be exported as javascript BLOB object and then uploaded to server.


Try it!

step by step video tutorial


UI Code

Uncomment and adjust the "uploadToServer" method as per your server side code domain and location.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Upload Image as IMG or Canvas and send to server as file or Blob</title>
    <style type="text/css">
    .table {
        display: table;
        border-collapse: separate;
        border-spacing: 10px 50px;
    .tableRow {
        display: table-row;
    .tableCell {
        display: table-cell;
    .box {
        border: 10px solid rgba(238, 238, 238, 0.5);

        <div class="table">
            <div class="tableRow">
                <div class="tableCell">
                    <input type="file" id="file">
                <div class="tableCell" id="fileInfo">

            <div class="tableRow">
                <div class="tableCell box">
                    <canvas id="panel"></canvas>
                    <button id="uploadCanvas">Upload Canvas</button>
                <div class="tableCell box">
                    <img src="" id="uploadedImage">
                    <button id="uploadImage">Upload Image</button>
        <script type="text/javascript">
        var imageUploader = {

            imageFile: null,

            canvasCtx: document.getElementById("panel").getContext("2d"),

             * Trigger this object by setting up basic events.
            init: function() {

                document.getElementById("uploadImage").onclick = this.uploadImage.bind(this);
                document.getElementById("uploadCanvas").onclick = this.uploadCanvasAsImage.bind(this);

                document.getElementById("file").onchange = function(event) {
                    this.imageFile =[0];
                    document.getElementById("fileInfo").innerHTML = "File Name: " + + "<br> Image type: " + this.imageFile.type;

                    var reader = new FileReader();
                    reader.onload = function(event) {
                        var img = new Image();
                        img.onload = function() {
                        img.src =;

             * Draw uploaded image on Canvas
            drawImageOnCanvas: function(img) {
                this.canvasCtx.canvas.width = img.width;
                this.canvasCtx.canvas.height = img.height;
                this.canvasCtx.drawImage(img, 0, 0);

                //Some update on canvas
                this.canvasCtx.font = "30px serif"
                this.canvasCtx.fillStyle = "rgba(0, 0, 0, 0.4)";
                this.canvasCtx.fillText(, 5, img.height - 8);

             * Basic image display as per the uploaded image.
            displayImage: function(img) {
                document.getElementById("uploadedImage").src = img.src;

             * canvas data uri return the Base64 encoded image, we need to conver into a binary file
             * before sending it to server.
            canvasToBlob: function(canvas, type) {

                var byteString = atob(canvas.toDataURL().split(",")[1]),
                    ab = new ArrayBuffer(byteString.length),
                    ia = new Uint8Array(ab),

                for (i = 0; i < byteString.length; i++) {
                    ia[i] = byteString.charCodeAt(i);

                return new Blob([ab], {
                    type: type

             * Upload basic image or file to server.
            uploadImage: function() {

                var data = new FormData();
                data.append("file", this.imageFile);


             * Add extra parmeter, in case of Canvas upload.
            uploadCanvasAsImage: function() {

                var data = new FormData();

                var blob = this.canvasToBlob(this.canvasCtx.canvas, this.imageFile.type);
                data.append("blob", blob);
                data.append("blobType", this.imageFile.type);


            uploadToServer: function(formData) {

                //Uncomment when you server ready

                xhr = new XMLHttpRequest();
      "post", "http://localhost:9999/icodingclub_web/fileUpload", true);
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4) {


         * Trigger the app.


Server side Code in Java

package com.fileupload.controller;


import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
maxFileSize = 1024 * 1024 * 5, // 5 MB
maxRequestSize = 1024 * 1024 * 10)
// 10 MB
public class FileUploadController extends HttpServlet {

 private static final long serialVersionUID = 1L;

 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  Part part = request.getPart("blob");
  String fileName = null;
  if (part != null) {
   //writing blob
   fileName = request.getParameter("blobName");
   part.write("path/to/upload" + File.separator + fileName);

  } else {
   //Writing image or file
   part = request.getPart("file");
   fileName = getFileName(part);
   part.write("path/to/upload" + File.separator + fileName);

  // Extra logic to support multiple domain - you may want to remove this
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.getWriter().print(fileName + " uploaded successfully");

 private String getFileName(Part part) {
  String contentDisp = part.getHeader("content-disposition");
  System.out.println("content-disposition header= " + contentDisp);
  String[] tokens = contentDisp.split(";");
  for (String token : tokens) {
   if (token.trim().startsWith("filename")) {
    return token.substring(token.indexOf("=") + 2,
      token.length() - 1);
  return "";

Contact Me

If you want to contact me for feedback or suggestion or doubt. You can do so by commenting on Blogger article or in Youtube contact section.

You can also approach me dropping me mail directly at


  1. Useful post. You have made a better path of providing the coding section. This post was really useful for me in gaining more knowledge. Thank you for taking your own time to provide us this useful and unique coding part which will help us in more time.
    Hadoop Training in Chennai Guindy


  2. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing

    dot net training in chennai

    php training in chennai

    java training in chennai

  3. Thank yoou for posting useful blog about coding .Request to visit
    Best msbi training in chennai

  4. Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    iOS Training in Chennai

  5. I was able to find good information from your blog posts.

    HTML5 Development

  6. This article is very much helpful and i hope this will be an useful information for the needed one. Keep on updating these kinds of

    informative things...

    Android App Development Company

  7. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    iOS App Development Company
    iOS App Development Company

  8. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    Fitness SMS
    Fitness Text
    Salon SMS
    Salon Text
    Investor Relation SMS
    Investor Relation Text

  9. great and nice blog thanks sharing..I just want to say that all the information you have given here is awesome...Thank you very much for this one.
    web design Company
    web development Company
    web design Company in chennai
    web development Company in chennai
    web design Company in India
    web development Company in India

  10. it is really amazing...thanks for sharing....provide more useful information...
    Mobile app development company

  11. this blog is really good and it is very much interesting and it has many information it is really helpful too. html5 training in chennai

  12. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Mobile Marketing Service
    Mobile Marketing Companies

  13. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

  14. Someone please help me... I am capturing image from webcam and try to store that image from canvas to server. I am not getting solution.