gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:48:51 24 4
gpt4 key购买 nike

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

最佳答案

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

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是一个演示,以备不时之需。

关于javascript - 如何在 Angular 的本地存储中存储文件(2 及更高版本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48474618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com