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

33 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. it is really amazing...thanks for sharing....provide more useful information...
    Mobile app development company

    ReplyDelete
  10. 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
  11. 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

    ReplyDelete
  12. 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

    ReplyDelete
  13. 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.

    ReplyDelete
  14. 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 HTML5 CSS3 Javascript Online Training from India . or learn thru HTML5 CSS3 Javascript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. HTML5 CSS3 Javascript Online Training from India

    ReplyDelete
  15. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end. aws interview questions for devops

    ReplyDelete
  16. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    Data Science Training in Chennai
    Data science training in bangalore
    Data science online training
    Data science training in pune
    Data science training in kalyan nagar
    Data science training in Bangalore
    Data science training in tambaram

    ReplyDelete
  17. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Devops training in Chennai
    Devops training in Bangalore
    Devops Online training
    Devops training in Pune

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete



  19. Wonderful article, very useful and well explanation. Your post is extremely incredible. I will refer this to my candidates...

    angularjs Training in bangalore

    angularjs Training in electronic-city

    angularjs Training in online

    angularjs Training in marathahalli

    ReplyDelete
  20. This is very good content you share on this blog. it's very informative and provide me future related information.
    python training in OMR
    python training in tambaram
    python training in annanagar

    ReplyDelete
  21. At this time, it seems like Word Press is the preferred blogging platform available right now. (from what I’ve read) Is that what you’re using on your blog? Great post, however, I was wondering if you could write a little more on this subject?
    Best AWS Training in Marathahalli | AWS Training in Marathahalli
    Amazon Web Services Training in Anna Nagar, Chennai |Best AWS Training in Anna Nagar, Chennai

    ReplyDelete
  22. 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.
    python training in rajajinagar
    Python training in btm
    Python training in usa
    Python training in marathahalli

    ReplyDelete
  23. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. 
    Devops Training in pune

    ReplyDelete
  24. Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up. 
    DevOps online Training
    Best Devops Training institute in Chennai

    ReplyDelete
  25. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.


    selenium training in electronic city | selenium training in electronic city | Selenium Training in Chennai

    ReplyDelete