0
batchDownloadImages() {
  const aTagDownload = [
    {
      download:'foo',
      href:'a HD image's long base64 str comes from canvas.toDataUrl()'
    },
    {
      download:'bar',
      href:'a HD image's long base64 str comes from canvas.toDataUrl()'
    }
  ]
  const a = document.createElement('a');
  aTagDownloadData.forEach((e) => {
    a.setAttribute('download', `${e.download}.jpg`);
    a.setAttribute('href', e.href);
    a.click();
  });
};

The method below can batch download images.

But when the HD image's size larger than a threshold value,its base64 string is too long so that a Tag's href attribute cannot hold the long base64 string.The final result is a failed download.

Long base64 image download failed

By the way, when I paste the long base64 string to Chrome's url bar,the tab broke.

Could anyone give me a solution to deal with the situation?

Thanks a lot.

frankkai
  • 145
  • 1
  • 2
  • 9
  • I think you're messing it up a little bith with the link stuff. You want to convert the base64 string into a blob object and download the blob. No link.click() or other weird stuff needed – user5328504 Mar 21 '19 at 03:20
  • @user5328504 Thanks a lot , I have solved it.But why 'No link.click() or other weird stuff needed ', is it unsafe? – frankkai Mar 21 '19 at 03:27
  • well, i think there are two problems: 1. it didnt work, 2. theres a more proper way using blobs. Honestly, I never thought of downloading stuff this way! – user5328504 Mar 21 '19 at 03:29
  • @user5328504 It does work.The blob opens my eye really, a amazing object.I'm ready to learn more about it. – frankkai Mar 21 '19 at 03:40
  • yeah, javascript (browsers, actually) are cooler every day. Keep it up! – user5328504 Mar 21 '19 at 03:43

1 Answers1

0

Transfer Base64 string to Blob url.

Before set the a Tag's href attribute value, transfer the base64 string to blob object and transfer the object to URL type.

Because the browsers have a maximum length in href attribute, but when we transfer the base64 string to blob url, the blob url is short enough to reach the href's working condition.

for example:


batchDownloadImages() {
  const aTagDownload = [
    {
      download:'foo',
      href:'a HD image's long base64 str comes from canvas.toDataUrl()'
    },
    {
      download:'bar',
      href:'a HD image's long base64 str comes from canvas.toDataUrl()'
    }
  ]
  const a = document.createElement('a');
  aTagDownloadData.forEach((e) => {
    a.setAttribute('download', `${e.download}.jpg`);
    this.dataURIToBlob(e.href, (blob) => {
      a.setAttribute('href', URL.createObjectURL(blob));
    });
    a.click();
  });
};

dataURIToBlob(dataURI, callback) {
  const binStr = atob(dataURI.split(',')[1]);
  const len = binStr.length;
  const arr = new Uint8Array(len);

  for (let i = 0; i < len; i++) {
    arr[i] = binStr.charCodeAt(i);
  }

  callback(new Blob([arr]));
},
frankkai
  • 145
  • 1
  • 2
  • 9