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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Convert the file to some kind of string encoding (Base 64) and save it as a string.
https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
回答2:
Here is a standalone service which works on Angular 7.
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.