Skip to content Skip to sidebar Skip to footer

Wait For User To Finish Downloading A Blob In Javascript

In Javascript, I'm creating a number of blobs that I want to prompt the user to save as files. At the moment, I'm doing that using URL.createObjectURL, placing the URL in a link,

Solution 1:

This is what worked for me.

/**
 *
 * @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
 */functionsaveObjectToFile (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}
 */exportasyncfunctiondownloadFileInBackground (path, payload, filenameWithExtension) {
  console.log('downloadFileInBackground awaiting fetch...')
  const response = awaitfetch(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:

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

Post a Comment for "Wait For User To Finish Downloading A Blob In Javascript"