无法设置 Blob 的文件名

ale*_*lex 3 javascript blob

我正在尝试自动下载这样的 blob:

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
})
Run Code Online (Sandbox Code Playgroud)

name或属性都download无法设置文件名,现在是:

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

如何正确设置文件名?

gue*_*314 6

Blob没有name属性。

保留原始元素type,并使用带有设置为 的属性的<a>元素,在将元素附加到 后调用元素。downloadhrefBlob URL.click()<a>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)
})
Run Code Online (Sandbox Code Playgroud)

  • 不需要 document.body.appendChild(a); 和 document.body.removeChild(a); (4认同)