3

I want to put a sample xlsx file in my public folder (react project) and others can download this file.

<Button><link rel="chargeSample" href="%PUBLIC_URL%/chargeSample.xlsx"></link></Button>

How can I do this?

Banafshe Alipour
  • 853
  • 2
  • 11
  • 25

3 Answers3

4

The tag defines a link between a document and an external resource. To let download funcionality on your website you should change link tag

import chargeSample from './public/chargeSample.xlsx';

<Button><a href={chargeSample} download="your file name">Download</a></Button>
  • 1
    i am stuck at this. downloading this way works locally, but when deployed to public, it fails and instead downloads just an empty corrupted file. Any ideas on that ? – Mohit Jun 17 '21 at 10:14
1

If you are using creat react app, you can pass public path into your components at build time by using

process.env.PUBLIC_URL
William Chou
  • 712
  • 4
  • 16
0

First of all, we have to think about where you store the file, thinking about what react is going to do in build time. In develop, you can't trust 100% that the paths you use are going to be the same after building the app. Here in the create react app doc there is some info about when to use the public folder and how to use it.

To download a file stored in the public folder, you have to reference it with the PUBLIC_URL. There are two ways of doing this:

Reference a file from inside the public folder
You will have to use de %PUBLIC_URL% as you mentioned. For example, if you want to use a fav icon in the main HTML file, you have to add the icon in the public folder and then in the index.html you will reference this file with the %PUBLIC_URL% prefix.

// public/index.html
// ...other stuff
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
// ...

In build time, React will replace this hash with the path to that folder

Reference a file in the src folder
To reference a file from inside the src folder, you have to access the public folder URL. React saves this path in an environment variable. To be able to use that file you have to use the process.env.PUBLIC_URL path.
To download a file from the public folder, you can access it like this:

<a
  href={process.env.PUBLIC_URL + "/my-file.txt"}
  download={"file-name-to-use.txt"}
>
    Download file
</a>

When clicking the anchor tag it will try to download the file stored in /public with the name my-file.txt and it will use as a placeholder name for that file the one specified in the download property.

Lucas
  • 31
  • 1
  • 3