如何在Angular的本地存储中存储FILE(2及更高版本) [英] How to store a FILE in Local Storage in Angular (2 and up)

查看:78
本文介绍了如何在Angular的本地存储中存储FILE(2及更高版本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to just store the image or pdf or any type of file in local storage.
So, is there a way to store a file in LocalStorage?

推荐答案

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

Here is a standalone service which works on 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

}

用法非常简单:

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.

这篇关于如何在Angular的本地存储中存储FILE(2及更高版本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆