admin管理员组

文章数量:1278910

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?

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?

Share Improve this question asked Jan 22, 2018 at 2:45 alexalex 7,61115 gold badges53 silver badges79 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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)
})

本文标签: javascriptCan39t set filename of BlobStack Overflow