简体   繁体   English

如何在 Angular 的本地存储中存储文件(2 及更高版本)

[英]How to store a FILE in Local Storage in Angular (2 and up)

I want to just store the image or pdf or any type of file in local storage.我只想将图像或 pdf 或任何类型的文件存储在本地存储中。
So, is there a way to store a file in LocalStorage?那么,有没有办法在 LocalStorage 中存储文件?

Here is a standalone service which works on Angular 6/7/8.这是一个适用于 Angular 6/7/8 的独立服务。
It downloads, stores and retrieves a file in local storage.它下载、存储和检索本地存储中的文件。

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map, flatMap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class OcFileStorageService {

  //#region Lifecycle methods

  constructor(private httpSvc: HttpClient) { }

  //#endregion Lifecycle methods

  //#region Exposed methods

  /**
   * Tries to retrieve base64 file from local storage.
   * If doesn't exist, downloads stores and retrieves the file again.
   * @param key Key to search in storage
   * @param urlIfNotExist Url which will be downloaded if key wasn't found
   * @returns Observable of base64 data url string with the file inside
   */
  public getStoredFile(key: string, urlIfNotExist: string): Observable<string> {
    const storedFile = this.getFromStorage(key);
    if (storedFile) {
      return this.objectToObserver<string>(storedFile);
    } else {
      return this.downloadDataAsBase64(urlIfNotExist).pipe(
        map((b64Result: string) => {
          this.saveToStorage(key, b64Result);
          return b64Result;
        })
      );
    }
  }

  //#region Exposed methods

  //#region Storage methods

  private saveToStorage(key: string, b64Result: string) {
    localStorage.setItem(key, b64Result);
  }

  private getFromStorage(key: string) {
    return localStorage.getItem(key);
  }

  //#endregion Storage methods

  //#region Downloader methods

  private downloadAsBlob(url: string) {
    return this.httpSvc.get(url, { responseType: 'blob' });
  }

  private downloadDataAsBase64(url: string): Observable<string> {
    return this.downloadAsBlob(url).pipe(
      flatMap(blob => {
        return this.blobToBase64(blob).pipe(
          map((b64Result: string) => {
            return b64Result;
          })
        );
      })
    );
  }

  //#endregion Downloader methods

  //#region Util methods

  private blobToBase64(blob: Blob): Observable<{}> {
    const fileReader = new FileReader();
    const observable = new Observable(observer => {
      fileReader.onloadend = () => {
        observer.next(fileReader.result);
        observer.complete();
      };
    });
    fileReader.readAsDataURL(blob);
    return observable;
  }

  private objectToObserver<T>(storedFile: T): Observable<T> {
    return new Observable<T>(observer => {
      observer.next(storedFile);
      observer.complete();
    });
  }

  //#region Util methods

}

Usage is quite simple:用法很简单:

constructor(private ocFileStorageSvc: OcFileStorageService) {}

ngOnInit() {
  this.ocFileStorageSvc
    .getStoredFile('quokka', 'https://pbs.twimg.com/media/DR15b9eWAAEn7eo.jpg')
    .subscribe((base64Data: string) => {
      this.quokkaImageData = base64Data;
    });
}

And here is a demo just in case you need.是一个演示,以防万一。

Convert the file to some kind of string encoding (Base 64) and save it as a string.将文件转换为某种字符串编码(Base 64)并将其另存为字符串。

https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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