Sae1962
Sae1962

Reputation: 1214

How to get the cached image of the browser?

I am implementing a Web page in JavaScript with Angular.JS & ionic. A page generator is one of the menu items that have a header field where the user can load a file. With the [Save] button, the result is sent to the relational database.

The page generator is saving the whole generated HTML object in the database like

<div class="hero-image" ivm-bg-axis="y" ivm-bg-drag="" ivm-bg-disabled="disabled" ng-style="imageOptions.style" ngf-background="ngModel" style="background-image: url(&quot;blob:null/3dfb1617-e1c8-45e8-9c0e-5f772129d2cb&quot;);"></div>

where the image is denoted with *style="background-image: url("blob:null/3dfb1617-e1c8-45e8-9c0e-5f772129d2cb");*. This is probably the unique key of the cached browser object, is it? If so, I want to save this image as a BLOB object, say, in another field of the same database record.

Question: How is it possible to get this image out of the browser? Is there a difference getting out this information between different browsers?

Thank you for your reply!

Edit: What I need in pseudo-code is something like this:

var cache = new BrowserCache();

var imageURL= cache.querySelector('url["blob:null/520cf0e0-fa19-438c-9db7-68af87f30f56"]');

var image = cache.getElement(imageURL);

// Convert image to appropriate format, if necessary
// Add image information to record to be sent to the server

Upvotes: 2

Views: 5656

Answers (1)

Are
Are

Reputation: 2241

Based on your pseudo-code and my comments, I'll try to compile it here and hopefully it helps.

As I said, this code must be executed in the same window where the blob was constructed. Otherwise there is no option of getting the file back.

function getBlobFromUrl (bUrl) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest()
    xhr.responseType = 'blob'
    xhr.addEventListener('load', event => {
      if (xhr.status === 200) {
        resolve(xhr.response)
      } else {
        reject(new Error('Cannot retrieve blob'))
      }
    })

    xhr.open('GET', bUrl, true)
    xhr.send()
  })
}

function fromBlobToBase64 (blob) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader()
    reader.addEventListener('loadend', event => {
      resolve(reader.result)
    })
    reader.readAsDataURL(blob)
  })
}

let blobUrl = 'blob:null/520cf0e0-fa19-438c-9db7-68af87f30f56'
getBlobFromUrl(blobUrl).then(fromBlobToBase64).then(result => {
  // result will contain file encoded in base64
})

Based on those two answers:

If you want to read more, there are links to relevant documentation:

Upvotes: 1

Related Questions