How to save an image to localStorage and display it on the next page?

后端 未结 7 2085
逝去的感伤
逝去的感伤 2020-11-22 07:31

So, basically, I need to upload a single image, save it to localStorage, then display it on the next page.

Currently, I have my HTML file upload:

<         


        
7条回答
  •  臣服心动
    2020-11-22 07:52

    If your images keep getting cropped, here's some code to get the dimensions of the image file before saving to localstorage.

    First, I would create some hidden input boxes to hold the width and height values

    
    
    

    Then get the dimensions of your file into the input boxes

    var _URL = window.URL || window.webkitURL;
    $("#file-input").change(function(e) {
        var file, img;
        if ((file = this.files[0])) {
            img = new Image();
            img.onload = function() {
                $("#file-h").val(this.height);
                $("#file-w").val(this.width);
            };
            img.onerror = function() {
                alert( "not a valid file: " + file.type);
            };
            img.src = _URL.createObjectURL(file);
        }
    });
    

    Lastly, change the width and height objects used in the getBase64Image() function by pointing to your input box values

    FROM

    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
    

    TO

    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = $("#file-w").val();
        canvas.height = $("#file-h").val();
    

    Also, you are going to have to maintain a size of about 300kb for all files. There are posts on stackoverflow that cover file size validation using Javascript.

提交回复
热议问题