Praveen Singh

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

Introduction


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.

DEMO

Try it!





step by step video tutorial


code



UI Code

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


<!DOCTYPE html>
<html>

<head>
    <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);
    }
    </style>

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


                </div>
            </div>
            <div class="tableRow">
                <div class="tableCell box">
                    <h2>Canvas</h2>
                    <canvas id="panel"></canvas>
                    <br>
                    <button id="uploadCanvas">Upload Canvas</button>
                </div>
                <div class="tableCell box">
                    <h2>Image</h2>
                    <img src="" id="uploadedImage">
                    <br>
                    <button id="uploadImage">Upload Image</button>
                </div>
            </div>
        </div>
        <br>
        <br>
        <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 = event.target.files[0];
                    document.getElementById("fileInfo").innerHTML = "File Name: " + this.imageFile.name + "<br> Image type: " + this.imageFile.type;

                    var reader = new FileReader();
                    reader.onload = function(event) {
                        var img = new Image();
                        img.onload = function() {
                            this.drawImageOnCanvas(img);
                            this.displayImage(img);
                        }.bind(this)
                        img.src = event.target.result;
                    }.bind(this);
                    reader.readAsDataURL(this.imageFile);
                }.bind(this);
            },

            /**
             * 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(this.imageFile.name, 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),
                    i;

                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);
                this.uploadToServer(data);

            },

            /**
             * 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("blobName", this.imageFile.name);
                data.append("blobType", this.imageFile.type);
                this.uploadToServer(data);

            },

            uploadToServer: function(formData) {

                //Uncomment when you server ready

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

            }
        }

        /**
         * Trigger the app.
         */
        imageUploader.init();
        </script>
    </body>

</html>




Server side Code in Java



package com.fileupload.controller;

import java.io.File;
import java.io.IOException;

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;

@WebServlet("/fileUpload")
@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 mails.icodingclub@gmail.com

12 comments:

  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


    ReplyDelete

  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

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

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

    iOS Training in Chennai

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

    HTML5 Development

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

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

    ReplyDelete
  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

    ReplyDelete