0

In Javascript (w/ Angular 2+) I have an app where I am trying to save a dataURl to localstorage once it has been picked by a user. Currently I have tried the following code but on retrieval I get an empty obj {} as the body.

HTML

<input style="display:none;" type="file" (change)="fileEvent($event)" #file>

Angular File Storage and Retrieval Function

fileEvent(ev: any): void {
    console.log('Event select file', ev);    
    let obj: any = ev.target.files[0];
    let file: File = {
      Key: obj.name,
      ContentType: obj.type,
      Size: obj.size,
      Body: obj      
    };
    localStorage.setItem("myapp", JSON.stringify(file);
}

getFileFromLocalStorage {
     console.log(JSON.parse(localStorage.getItem("myapp"));
}

File Retrieval Response below

enter image description here

Zooly
  • 4,736
  • 4
  • 34
  • 54
Ka Tech
  • 8,937
  • 14
  • 53
  • 78
  • There is one typo here `localStorage.setItem("myapp", JSON.stringify(file);` the closing brace `)` is missing – brk May 02 '18 at 07:41
  • Possible duplicate of [How to get full path of selected file on change of using javascript, jquery-ajax?](https://stackoverflow.com/questions/15201071/how-to-get-full-path-of-selected-file-on-change-of-input-type-file-using-jav) – Muhammad Usman May 02 '18 at 07:43
  • What you want is [IndexedDB](https://developer.mozilla.org/en/docs/Web/API/IndexedDB_API), which usage is greatly simplified by Mozilla's [localforage](https://github.com/localForage) lib. But I even wonder if Angular doesn't have its own wrapper for IndexedDB, but I'm quite ignorant when it's about Angular... – Kaiido May 02 '18 at 07:59

1 Answers1

1

You can not store image directly to localstorage like this. First you need to convert the image to Base64. Then save the Base64 string in localStorage value.

Below is function to convert Image into Base64:

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

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Now you can save this to your local storage.

Here is the reference answer on SO.

Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
  • Don't store an image in localStorage, localStorage is not meant to store binary data. Instead use IndexedDB which is meant for this task and will be able to store the File as File. And don't use a canvas to convert an image File to b64, use a FileReader instead. – Kaiido May 02 '18 at 07:56
  • Thanks for this I will give canvas a go. @Kaiido if you suggest FileReader how would I do this? Ps I am using a plugin which will prioritise IndexedDB over local storage. – Ka Tech May 02 '18 at 11:46