Danny Fox
Danny Fox

Reputation: 40799

How to store files with JS?

I want to store images and sounds using JS. Is there any API for this, like the localstorage? Unfortunatly in the localstorage I can only save text.

Upvotes: 1

Views: 1019

Answers (3)

kujakettu
kujakettu

Reputation: 118

It is also possible to base64 encode files and then save them to localStorage. You can find more information on encoding and saving images here.

Upvotes: 1

katspaugh
katspaugh

Reputation: 17939

While you could store files manually (with Google Chrome's File API), the intended approach is caching. Cache is a straightforward way to store your media seemingly automatically.

It's only a matter of writing a manifest:

CACHE MANIFEST
blast.ogg
styles.css
images/gun.png

After the first load of these files, you just load them again as usual, but they come from the disk instead of your server. It works when the browser is off-line, too.

It also degrades nicely: unsupported browsers would simply manage the cache as they see feet.

Here's a tutorial by Google at HTML5Rocks.

Upvotes: 2

Sirko
Sirko

Reputation: 74106

You have no access to the local filesystem via JavaScript in a browser. This is due to the sandboxing and is a major feature of the security model inside a browser.

Regarding localStorage, you may store just text, but with the help of JSON.stringify() and JSON.parse() you can store almost any object or data you come across in JavaScript.

Upvotes: 1

Related Questions