0

I get a file inputted in file input using file reader and store it in another object which I store in localStorage using JSON.stringify it returns an empty object {}. Then, when I use JSON.parse I get an empty object ('{}')

//getting the file
const contacts = []
const fileInput = document.querySelector("input[type=\"file\"]")
fileInput.addEventListener("change", () => {
  const pic = fileInput.files[0]
  contacts.push({pic}) //plus other details
  localStorage.setItem("contacts", JSON.stringify(contacts))

  console.log(fileInput.files[0])//returns a file object
  console.log(JSON.stringify(fileInput.files[0]))//returns an empty
})
<input type="file">

Is there any way to store it in the localStorage in a way that when it is parsed a file object is returned?

  • https://stackoverflow.com/questions/21008732/javascript-save-blob-to-localstorage – spender May 28 '22 at 10:30
  • See the linked questions. Basically: No, you can't store a `File` object in `localStorage`, but you can read the file and store its contents, then later read the contents from `localStorage` to create a `Blob` (which isn't a `File`, but most of the useful things `File` has it inherits from `Blob`). That said, I really wouldn't recommend storing a file in `localStorage`, you're very likely to hit the storage limits. – T.J. Crowder May 28 '22 at 10:31
  • @T.J.Crowder any other ideas of how I can store a file(without using a server or any kind of back-end)? How can I do that Blob stuff you said without using AJAX(I use only local images which the user is supposed to input) – Kaustubh Maladkar May 28 '22 at 11:30
  • 1
    No, I can't think of any other way to save a file locally. The linked question's answers go into how to create a `Blob` from a string you get back from `localStorage` (or there's [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Blob)). – T.J. Crowder May 28 '22 at 11:43

0 Answers0