Efficient way to save a File object locally for later use

Asked

Viewed 20 times

0

Hello! I am developing a web app, and in it uploading files are done.
When the user is offline (it’s a PWA) I need to save these files locally to upload later. I cannot save a File object directly to localStorage, so I am using this function to convert the contents of the file into an array of bytes, use JSON.stringify to convert the array in a JSON string and then save to localStorage:

async function FileToJSONString(file, callback) {
    console.log(file);
    let result =
    await file
    .stream()
    .getReader()
    .read();

    let value = result.value;
    callback(JSON.stringify(value))
}

Problem: The problem is that saving the file contents in this way uses a lot of space and has a high cost of performance.

Question: Is there another more appropriate way to save the file locally? (I don’t mind using another form of storage other than localStorage)

  • Where does that come from file? What is he?

  • 1

    Maybe one option is to use the API Indexeddb.

  • 1

    @Luizfelipe The file comes from an HTML file input: <input>.files. https://developer.mozilla.org/en-US/docs/Web/API/File

  • @Luizfelipe worked perfectly with Indexeddb. Grateful.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.