问题
<img src="picture_1.png" id="imgHolder"/>
Would like to save image with indexedDB in database named Images on button click.
<button id="write" onclick="saveToDB()">Save To DB</button>
Another button will read image from Images database to display in <div id="resultContent"/>
.
<button id="read" onclick="readFromDB()">Read from DB</button>
回答1:
General idea is:
- Create a database with a specified name. Use indexedDB.open() for that.
- Create an objectStore.
- Read a file(image in your case) as blob. Use XMLHttpRequest for that.
- Create a db transaction.
- Save file blob in th DB.
- Read file blob from database.
- Create URL using URL.createObjectURL() function
- Insert url in src attribute in an image tag.
See more: https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/
回答2:
Yes this is possible. Inside of @Yauhen's answer is a link to a Mozilla article that can explain one possible implementation. I'll offer some additional context and an alternative solution using canvas
.
indexedDB
is an indexed key/value store that can store any type of JavaScript object that can be so-called "cloned." A handy heuristic is that essentially anything you can pass to a Web Worker you can pass to IDB.
To store images, you turn them into strings. Strings can be cloned, so they can saveToDB()
and readFromDB()
without issue.
One way to turn an image into a string representation is createObjectURL(), which you do on a URL
object. My preferred method is toDataURL()
which are found on canvas Either way you're looking at intermediate steps to 1) load your image to either a blob or a canvas then 2) extract that data into a storable string.
来源:https://stackoverflow.com/questions/22740186/using-indexeddb-to-save-images