且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

等待用户在 Javascript 中完成下载 blob

更新时间:2023-01-04 22:22:58

这对我有用.

/**
 *
 * @param {object} object A File, Blob, or MediaSource object to create an object URL for. https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
 * @param {string} filenameWithExtension
 */
function saveObjectToFile (object, filenameWithExtension) {
  console.log('saveObjectToFile: object', object, 'filenameWithExtension', filenameWithExtension)
  const url = window.URL.createObjectURL(object)
  console.log('url', url)
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.target = '_blank'
  link.download = filenameWithExtension
  console.log('link', link)
  document.body.appendChild(link)
  link.click()
  window.setTimeout(function () {
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  }, 0)
}

/**
 * @param {string} path
 * @param {object} payload
 * @param {string} filenameWithExtension
 * @returns {promise}
 */
export async function downloadFileInBackground (path, payload, filenameWithExtension) {
  console.log('downloadFileInBackground awaiting fetch...')
  const response = await fetch(path, {
    method: 'POST',
    cache: 'no-cache',
    headers: {
      'Content-Type': 'application/json'
    },
    body: payload // body data type must match "Content-Type" header
  })
  console.log('response', response)
  const blob = await response.blob()
  saveObjectToFile(blob, filenameWithExtension)
  console.log('downloadFileInBackground finished saving blob to file!', filenameWithExtension)
}

我知道其他人也有这个问题:

I know other people have this problem too:

附:我很欣赏@sicking 在 https://github.com/whatwg/的想法html/issues/954#issue-144165132.

P.S. I appreciate the idea from @sicking at https://github.com/whatwg/html/issues/954#issue-144165132.