0

I am trying to capture an image using HTML an input tag for file image capture. And save it to local storage before submission. For offline use in a web app

I am using:

<input type="file"
   name="picture"
   accept="image/*"
   capture="user">

All I can find is how to save an image already on the page to local storage, or from a canvas, but not from Form Data.

Thanks.

Enjabain
  • 181
  • 1
  • 8
  • Does this answer your question? [Javascript FileReader Multiple Images](https://stackoverflow.com/questions/29218333/javascript-filereader-multiple-images) – Dean Van Greunen Jun 22 '23 at 11:40

1 Answers1

1

You need to create a FileReader that read the content of the image, and when loaded, store to localStorage (localStorage does not work here on SO).

const img = document.getElementById('img');

document.forms.form01.addEventListener('submit', e => {
  e.preventDefault();
  let data = new FormData(e.target);
  var reader = new FileReader();
  reader.addEventListener('loadend', e => {
    img.src = e.target.result;
    // save to localStorage
    //localStorage.setItem('picture', e.target.result);
  });
  reader.readAsDataURL(data.get('picture'));
});
<form name="form01">
  <input type="file" name="picture" accept="image/*" capture="user" required />
  <button>Save</button>
</form>
<img id="img" />
chrwahl
  • 8,675
  • 2
  • 20
  • 30