Thach Nguyen
Thach Nguyen

Reputation: 76

HTML5 download attribute not working when download external PDF file on Chrome

The code is very simple:

<a download href="http://www.pdf995.com/samples/pdf.pdf">Download</a>

I expect it to save the pdf file but it always open the file on the browser.

It works with other file type, just have problem with PDF file.

Upvotes: 1

Views: 5530

Answers (2)

Karl Horky
Karl Horky

Reputation: 4944

If the URL that you're trying to fetch has an Access-Control-Allow-Origin header, you can work around this by using fetch and blobs:

function forceDownload(blob, filename) {
  // Create an invisible anchor element
  const anchor = document.createElement('a');
  anchor.style.display = 'none';
  anchor.href = window.URL.createObjectURL(blob);
  anchor.setAttribute('download', filename);
  document.body.appendChild(anchor);

  // Trigger the download by simulating click
  anchor.click();

  // Clean up
  window.URL.revokeObjectURL(anchor.href);
  document.body.removeChild(anchor);
}

function downloadResource(url, filename) {
  fetch(url, {
    headers: new Headers({
      Origin: window.location.origin,
    }),
    mode: 'cors',
  })
    .then(response => response.blob())
    .then(blob => forceDownload(blob, filename))
    .catch(e => console.error(e));
}

downloadResource('https://memegen.link/xy/fetch/all_the_things.jpg?watermark=none');

This has a few limitations:

  • the file size limit of blobs is about 500MB
  • some websites will not allow for cross-origin requests, leading to errors like this one below

Failed to load https://example.com/example.jpg: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access.

Ref 1: Leeroy in https://stackoverflow.com/a/49500465/1268612

Ref 2: https://davidwalsh.name/javascript-download

Full explanation: https://blog.logrocket.com/programmatic-file-downloads-in-the-browser-9a5186298d5c/

Upvotes: 4

Quentin
Quentin

Reputation: 944016

See the MDN documentation:

This attribute only works for same-origin URLs.

Presumably, the other file types, where you see it "working", are ones where the default behaviour is to download the file.

Upvotes: 7

Related Questions