How to store binary files in localStorage
localStorage
can only store Strings, while modern Javascript can also handle binary files. For example, the result of a fetch
can be retrieved as a Blob
.
How to store binary data in a storage that only supports Strings?
Most examples show how to store images, but that uses only the Blob
=> String part of the conversion, as images can be shown using a Data URL. For other types, it is usually a requirement to be able to retrieve the stored data in binary form.
Blob
-> String
To convert a Blob
(for example, an uploaded file, or the result of a fetch
), use a FileReader
:
const reader = new FileReader();
reader.onload = (event) => {
localStorage.setItem("file", event.target.result);
}
reader.readAsDataURL(blob);
String -> Blob
Unfortunately, there is no built-in function that does the conversion the other way. But there are some scripts, like this one that provides the missing piece.
dataURItoBlob(localStorage.getItem("file")) // Blob
Alternatives to localStorage
While localStorage
is great as its simple API makes integration a breeze, it has many downsides.
For one, its storage quota is low, as you can expect it to be just around 5 MBs, and it is even inconsistent among the browsers. To make things worse, the Data URL format is ineffective compared to binary, swelling the data to multiple times its original size.
For any serious use, consider IndexedDb
, which supports both binary data and higher quotas.