Javascript 下载Readablestream作为文件

Javascript 下载Readablestream作为文件,javascript,Javascript,我从api中获得一个可读流。如何将整个可读流转换为createObject URL,以便下载文件 // res.body is a readable stream // const reader = res.body.getReader() // console.log(reader) const contentDisposition = res.headers.get("content-disposition") const contentType = re

我从api中获得一个可读流。如何将整个可读流转换为createObject URL,以便下载文件

// res.body is a readable stream
  // const reader = res.body.getReader()
  // console.log(reader)
  const contentDisposition = res.headers.get("content-disposition")
  const contentType = res.headers.get("content-type")
  const filename = contentDisposition.match(/filename="(.+)"/)[1]
  const file = new Blob([res.body], { type: contentType }) // this is not working
  const objectUrl = URL.createObjectURL(file)

  const a = document.createElement("a")
  document.body.appendChild(a)
  a.style = "display: none"
  a.href = objectUrl
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(objectUrl)

使用此代码解决此问题

.then((response) => response.blob())
.then((blob) => URL.createObjectURL(blob))
.then((href) => {
  const a = document.createElement("a")
  document.body.appendChild(a)
  a.style = "display: none"
  a.href = href
  a.download = fileName
  a.click()
})

这个代码毫无意义。。。如果不打算将整个ReadbleStream部分作为流使用,则可以删除它。只需执行
。然后((response)=>response.blob())
从头开始。这就像做
str1=“hello”;str2=str1.split(“”).map(c=>String.fromCharCode(c.charCodeAt(0)).concat(“world.split(“”)).join(“”)而不是
str2=str1+“world”
为什么不呢?不确定。我尝试了许多替代方案,并用上面的答案回答了endedup。没有理由你可以将这个身体作为一个可读的流而不是直接作为一个Blob来使用。你尝试的时候肯定做错了什么。我也不知道为什么这样做有效,但它帮我节省了很多时间!非常感谢。