11

I've built a simple web app which creates an image from a canvas element using canvas.toDataURL(). I then create an anchor tag using the data URI, containing a download attribute. Something like this:

<a href="data:image/jpeg;base64,somedata" download="filename.jpg">Download</a>

This works great on Android/MacOS devices on Chrome and Safari - clicking the anchor downloads the data URI as a .jpg file.

But on iOS Chrome clicking the link does nothing. To download the file it requires opening the anchor in a new tab (which displays the image), then saving the image.

I have tried adding a target="_blank" but that does not achieve the desired result.

Is there a way to make iOS work like Android/MacOS, where clicking the link initiates the download?

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
  • I don't think you can download files on iOS like you can on other devices. It's really different since it doesn't have the same type of file system as normal devices. – Charlie Fish Dec 29 '18 at 18:14
  • check this https://stackoverflow.com/questions/53666113/file-not-downloading-with-blob-object-in-iphone-chrome-browser. Using FileReader can resolve this issue. but only for ios. – Micheal Vu Jan 09 '20 at 02:35

1 Answers1

0

Unfortunately, it seems that on iOS devices, the behavior of the download attribute for a tags is different than on Android and MacOS devices. On iOS, when the download attribute is used with a data URI, the browser will open the data in a new tab instead of initiating a download.

There are a few workarounds you could try to achieve the desired behavior on iOS:

  1. Use JavaScript to trigger the download: Instead of using an anchor tag with the download attribute, you can use JavaScript to trigger the download by creating a new Blob object with the data URI and then creating a new URL object with the Blob. Then, you can use the URL.createObjectURL() method to create a new link and use the a.href and a.download to set the link and download name.

  2. Use a server-side script to handle the download: You could pass the data URI to a server-side script (like a PHP script) and have it convert the data URI to a file, then set the appropriate headers to trigger the download.

  3. Use a third-party library: There are a few libraries out there that can help with this issue, like downloadjs and file-saver. These libraries provide a cross-browser compatible way to handle downloads in JavaScript.

Keep in mind that these solutions may have some limitations, for example, using JavaScript to trigger the download may not work on all browsers and using a server-side script may add some latency to the download process.