简体   繁体   中英

Javascript: How to save file location to local storage?

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

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM