Using IndexedDB to save images

前端 未结 2 1795
甜味超标
甜味超标 2021-02-20 07:10

Would like to save image with indexedDB in database named Images on button click.

&         


        
相关标签:
2条回答
  • 2021-02-20 07:48

    General idea is:

    1. Create a database with a specified name. Use indexedDB.open() for that.
    2. Create an objectStore.
    3. Read a file(image in your case) as blob. Use XMLHttpRequest for that.
    4. Create a db transaction.
    5. Save file blob in th DB.
    6. Read file blob from database.
    7. Create URL using URL.createObjectURL() function
    8. Insert url in src attribute in an image tag.

    See more: https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/

    0 讨论(0)
  • 2021-02-20 08:00

    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.

    0 讨论(0)
提交回复
热议问题