2

I want to download pdf file directly without viewing, i have tries following things till now but nothing is helping.

1- window.open("https://s3-link1.pdf", 'Download');

2- <a href="https://s3-link1.pdf" download>Link</a>

Link - https://s3-link1.pdf

Assume my domain is https://www.somedomain.com

I somewhere read we can't download cross-origin files. content-disposition header is required to be passed from backend. I am puzzled here. Another csv file of cross-origin is being downloaded easily.

https://s3-link2.csv

I just need to download pdf file using javascript. Please guide me.

Pooja Verma
  • 133
  • 4
  • 14

2 Answers2

3

Try with fetch.

fetch("https://s3-link1.pdf", {
    method: 'GET'
}).then(resp => resp.blob())
    .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.download = "name"; // the filename you want
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
    })
Pooja Verma
  • 133
  • 4
  • 14
Anup
  • 589
  • 4
  • 8
0

Option 1: with jQuery you can try this:

$.get("https://s3-link1.pdf", function (result)
{
    var blob = new Blob([result]);
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = "myFileName.pdf";
    link.click();
});

Option 2: The download attribute works in all modern browsers, including MS Edge, but not Internet Explorer.

In the latest versions of Chrome, you cannot download cross-origin files (they have to be hosted on the same domain).

<a href="https://s3-link1.pdf" download>Download PDF</a>

Find more about it here on this blog: https://actualwizard.com/html-force-download-file

Pooja Verma
  • 133
  • 4
  • 14
Rumplin
  • 2,703
  • 21
  • 45
  • Option 2: cross-origin link is working using window.open(), csv gets downloaded easily but not if it's a pdf. why so? https://supply-guide.s3-ap-southeast-1.amazonaws.com/CAMPAIGN_PROPERTIES_LIST_1597153535597.csv – Pooja Verma Sep 03 '20 at 12:19
  • 1
    it's not downloading, it's following the URL, and for that file type 'csv' the browser does the default action of saving the file, whereas with 'pdf', the default action is to open the file in the browser. When using the 'download' attribute, you might encounter the CORS problem. – Rumplin Sep 03 '20 at 12:23