0

I have a publicly accessible url to a PDF in Google Cloud Storage. I want to be able to create a button/link in react which allows users to download this PDF to their own computer. I'm wondering what is the best approach to do this and which libraries would be of help? Is there any documentation on this? Thanks

Soni Sol
  • 2,367
  • 3
  • 12
  • 23
Allen Wu
  • 165
  • 1
  • 2
  • 10
  • Maybe I'm missing the issue - have you tried a regular ` – Dean James Dec 23 '20 at 17:05
  • I tried the answer here:https://stackoverflow.com/questions/50694881/how-to-download-file-in-react-js but it just opens a tab with the file. I'm trying to allow the user to download the file to their computer when clicked. I am using chrome – Allen Wu Dec 23 '20 at 17:06
  • In order to get better help, your question should show specifically what you tried that doesn't work the way you expect. – Doug Stevenson Dec 23 '20 at 17:15

2 Answers2

0

In order to force download a file, you have a number of options. First, the easiest is using the download attribute of an anchor tag:

<a href="foo.pdf" download target="_blank">PDF</a>

However, this is not supported on IE and a number of other browsers in their earlier versions. But the maximum impact of this is it will open in a new tab which in my opinion is graceful degradation. See the full list of supported versions.

If this is not enough, you have to make some changes server-side. You can configure a server in many ways, but as an example, a .htaccess file can have the following:

<Files *.pdf>
    Header set Content-Disposition attachment
</Files>
Dean James
  • 2,491
  • 4
  • 21
  • 29
-1

You can dynamically generate a link or button. Snippet bellow:

var sampleBytes = new Int8Array(4096); // In your case it should be your file

var saveByteArray = (function () {
  var a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";

  return function (data, name) {
    var blob = new Blob(data, {type: "octet/stream"}), // or application/pdf
        url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = name;
    a.click();
    window.URL.revokeObjectURL(url);
  };
}());

saveByteArray([sampleBytes], 'example.txt'); // You can define the filename