Your files are stored on the server, AWS S3, and CloudFront. You must also develop a link, a button, that may utilize a URL to download these files to the user's PC. This will be covered further down;
In this example, I'll show you how to download a file from AWS S3 CDN (Cloudfront) to your local.
Demo: https://onurdayibasi.dev/json-url-download
https://onurdayibasi.dev/json-url-download
The code is quite simple. We create a DownloadLink component. This component gives the URL of the file to be downloaded and the name of the file to be saved as a file when saving it locally.
import { Button } from "antd";
import React from "react";
export const DownloadLink = ({ url, fileName }) => {
const handleDownload = () => {
fetch(url)
.then((response) => response.blob())
.then((blob) => {
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement("a");
link.href = url;
link.download = fileName || "downloaded-file";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
})
.catch((error) => {
console.error("Error fetching the file:", error);
});
};
return (
<div>
<Button type="primary" onClick={handleDownload}>
Download Sample JSON
</Button>
</div>
);
};
Then we send this parameter information to this component, which determines the file to download to our program.
const renderDemo = () => {
const downloadUrl =
"https://d3jy31tj1gt845.cloudfront.net/reactdigitalgarden/json/menu.json";
return (
<div>
<Typography.Text>Sample JSON File</Typography.Text>
<DownloadLink url={downloadUrl} fileName="menu.json" />
</div>
);
};
The file will be downloaded to our local PC when we push the button.
You can download the sample project by pressing the download button and run it on your local machine.