File stream in the background, receiving and downloading in the foreground

createObjectURL

The URL.createObjectURL() static method will create a URL pointing to the parameter object based on a DOMString passed in. The life cycle of this URL is bound to the document in the window that created it. The new object URL points to the executed File object or Blob object.

Each time  createObjectURL() the method is called, a new URL object is created. When these URL objects are no longer needed, each object must be  URL.revokeObjectURL() released by calling a method. The browser will automatically release them when the document is unloaded, but they should be actively released.

example

axios({
    method: 'get',
    url: url,
    params: params,
    responseType: 'blob',
}).then(response => {
    const filename = response.headers['content-disposition'].split('filename=')[1];
    const blob = new Blob([response.data], { type: 'application/pdf;charset=utf-8' });
    // 浏览器打开
    const href = window.URL.createObjectURL(blob);
    window.open(href);
    // 浏览器打开
    const aEl = document.createElement('a');
    aEl.style.display = "none";
    aEl.target = "_blank";
    aEl.href = URL.createObjectURL(blob);
    document.body.appendChild(aEl)
    aEl.click();
    document.body.removeChild(aEl)
    // 下载
    const aEl2 = document.createElement('a');
    aEl2.download = filename; // 这里写你的文件名
    aEl2.style.display = "none";
    aEl2.href = URL.createObjectURL(blob);
    document.body.appendChild(aEl2)
    aEl2.click();
    document.body.removeChild(aEl2)
  })

The difference between URL.createObjectURL  and FileReader.readAsDataURL(file)

createObjectURL 

  • Through URL.createObjectURL(blob)a memory URL that can get the current file;
  • createObjectURLis executed synchronously (immediately);
  • createObjectURLReturn a url with a hash, and it will be stored in memory until the document triggers unloadan event or executes revokeObjectURLto release;
  • Use createObjectURLcan save performance and be faster, you need to manually release memory when not in use;

readAsDataURL

  • FileReader.readAsDataURL(file)A string can be obtained through data:base64;
  • FileReader.readAsDataURLis executed asynchronously;
  • FileReader.readAsDataURLIt returns base64 containing many characters, and consumes more memory than blob url, but it will be automatically cleared from memory (through garbage collection mechanism) when not in use;
  • If you don't care much about device performance and want to get the base64 of the image, it is recommended to useFileReader.readAsDataURL;

Guess you like

Origin blog.csdn.net/my__flower/article/details/129812411