Search code examples
jqueryautosave

Autosave Form along with image using jQuery


Can anybody suggest me a jquery plugin that will auto save html forms data to LocalStorage to restore them after browser crashes,tabs closings or other disasters ?

I have used this one,its works fine,but it does not save image ?

Any suggestion would be highly appreciated.


Solution

  • ok, you could keep that component but extend what you need to cover the image upload. I'm assuming you want it on the 'change' event of the file input so:

    <input type="file" id="myimage" name="myimage" />
    

    EDIT here is a better example - then in JS:

    $(document).ready(function() {
        $("#myimage").on('change', function() {
            getImage(this);
        });
    });
    
    function getImage(e) {
        var reader = new FileReader();
        reader.onload = function(event) {
    
        var img = new Image();
        img.onload = function() {
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);
    
            var dataURL = canvas.toDataURL("image/png");
            console.log(dataURL);
            var base64Data = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    
            localStorage.setItem("myImageData", base64Data);
    
            setImage(); //set the image from the base64 string.
          }
          img.src = event.target.result;
        }
        reader.readAsDataURL(e.files[0]);
    }
    

    Then to read and set the image back on the page:

    <img id="myImageElement" src="" />
    
    function setImage() {
        try {
        var imgObj = $("#myimageElement");
    
        var base64Data = localStorage.getItem("myImageData");
        imgObj.src = "data:image/png;base64," + base64Data;
        }
        catch(e) {}
    }