K
K
Kneepy2021-08-15 17:06:25
JavaScript
Kneepy, 2021-08-15 17:06:25

How to store blob in db?

There is a link like

blob:http://localhost:8080/ad028394-c137-4842-aeeb-24c74fea28de
received as a result new Blob([file], { type: "image/png" });and subsequent URL.createObjectURL(blob), when you try to display this link in img, an error occurs
GET blob:http://localhost:8080/ad028394-c137-4842-aeeb... net::ERR_FILE_NOT_FOUND

And yes, I perfectly understand that even in the official documentation it is written
The generated url is only valid while the current document is open.

But the question is, is it possible in some way to store these files as a link without converting to base64

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2021-08-16
@zkrvndm

If it happens in the browser, you can save the files in IndexedDB and they will remain there even after reloading the page. To store a file in IndexedDB , first include the localforage library on the page :

<script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.9.0/localforage.min.js"></script>

Then you can safely throw the file into the browser's memory like this:
async function saveFile(file) {
    var result = await localforage.setItem('file', file);
    console.log('Файл сохранён:');
    console.dir(result);
}

Call the saveFile function with the file you want to save as an argument.
To then extract this file from memory and insert it into the src tag of the image:
async function getFile() {
    var file = await localforage.getItem('file');
    document.querySelectror('img').src = URL.createObjectURL(file);
    console.log('Файл вставлен:');
    console.dir(file);
}

Just call the getFile function.
You can read more about the localforage library here:
https://html5.by/blog/localforage/
Above are just examples. To finish it for yourself, I recommend that you get acquainted with what promises are and how asynchronous functions differ from ordinary ones + try to understand how async / await works.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question