1

I'm trying to upload and store Profile image in local storage (for one demo purpose) using jquery. I just did upload part and don't know how to store that image in local storage. Please check this fiddle and help me to sort this out. Thanks.

 function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#bannerImg').attr('src', reader.result);
    }
    reader.readAsDataURL(input.files[0]);
  }
}

$(".file-upload").change(function() {
  readURL(this);
});

$(".upload-button").on('click', function() {
  $(".file-upload").click();
});
ilmk
  • 599
  • 1
  • 9
  • 19
  • converting image to base64 might help you too, http://stackoverflow.com/questions/19017401/how-to-store-and-retrieve-image-to-localstorage – Mohammad Kermani May 07 '17 at 06:06

2 Answers2

2

Save file as base64 and load it from localstorage onload .Hope this helps you.
https://jsfiddle.net/RemyaJ/f9wfftft/4/

if(localStorage.img) { 
    $('#bannerImg').attr('src', localStorage.img);
    }
    function readURL(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
        localStorage.setItem('img', e.target.result);
          $('#bannerImg').attr('src', reader.result);
        }
        reader.readAsDataURL(input.files[0]);
      }
    }

    $(".file-upload").change(function() {
      readURL(this);
    });

    $(".upload-button").on('click', function() {
      $(".file-upload").click();
    });
RemyaJ
  • 5,358
  • 4
  • 22
  • 41
0

You can not upload file only with Jquery, You need at least php function (run on a web server) to upload them to your local directory.

First thing first, you need to add and id attribute to your input on your html code:

<input class="file-upload" type="file" id="file" accept="image/*" />

Then, add this function below your readURL:

$(".file-upload").change(function() {
 readURL(this);
 var input = document.getElementById("file");
 file = input.files[0];
 if(file != undefined){
   formData= new FormData();
   if(!!file.type.match(/image.*/)){
     formData.append("image", file);
     $.ajax({
       url: "upload.php",
       type: "POST",
       data: formData,
       processData: false,
       contentType: false,
       success: function(data){
           alert('success');
       }
     });
   }else{
     alert('Not a valid image!');
   }
 }else{
   alert('Input something!');
 }
});

Then, create another file, let say upload.php

<?php
$dir = "your local storage directory";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_FILES["image"]["name"]);
?>

You could also read this article for better understanding.

DedenB
  • 50
  • 8