alex
alex

Reputation: 7611

Can't set filename of Blob

I'm trying to automatically download a blob like this:

blobGeneratingFunction.then(blob => {
  // blob => Blob(3797539) {size: 3797539, type: "image/png"}
  let file = new Blob([blob], { type: 'application/octet-stream' })
  file.name = 'test.png'
  file.download = 'test.png'
  let blobURL = URL.createObjectURL(file)
  window.location.href = blobURL
})

Neither the name or download attribute managed to set the filename, which right now is:

f486177d-6f5e-4f96-91a9-8df08e7d9da0

How to set the filename propertly?

Upvotes: 3

Views: 13457

Answers (1)

guest271314
guest271314

Reputation: 1

Blob does not have a name attribute.

Preserve the original type, and use <a> element with download attribute with href set to to the Blob URL, call .click() on <a> element after appending the element to document.body.

blobGeneratingFunction.then(blob => {
  let a = document.createElement("a") 
  let blobURL = URL.createObjectURL(blob)
  a.download = 'test.png'
  a.href = blobURL
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
})

Upvotes: 9

Related Questions