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
Asked
Active
Viewed 4,453 times
0
-
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 Answers
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
-
I tried this example in chrome: PDF however it still just opens the pdf in a new tab and doesn't download to the user's computer – Allen Wu Dec 23 '20 at 17:16
-
I'm not sure what that issue is - you can see this working here: https://codesandbox.io/s/vibrant-wiles-21xu4. – Dean James Dec 23 '20 at 17:58
-
-
-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

Alexander B.
- 44
- 6