如何在Angular(2及以上)的本地存储中存储文件

时间:2018-01-27 09:59:19

标签: javascript angular local-storage

我想将图片或pdf或任何类型的文件存储在本地存储中 那么,有没有办法在LocalStorage中存储文件?

2 个答案:

答案 0 :(得分:0)

将文件转换为某种字符串编码(Base 64)并将其另存为字符串。

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

答案 1 :(得分:0)

这是可在Angular 7上运行的独立服务。
它下载,存储和检索本地存储中的文件。

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

}

用法非常简单:

constructor(private ocFileStorageSvc: OcFileStorageService) {}

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

here是一个演示,以备不时之需。