skip to Main Content

I am trying to download a CSV file which resides in my project assets folder by clicking an anchor tag. But when i do this i got an error message like this ""File wasn’t available on site". Tried many solutions, but none of them work.

My snippets are below. Any help is much appreciated.

 <a href="/assets/UserListSample.csv" download="UserListSample.csv">
    Click here
 </a>

2

Answers


  1. You’ve got two options:

    1 Import the file

    import UserListSample from 'path/to/the/assets/UserListSample.csv';
    
    export default function DownloadAnchor() {
      return (
        <a href={UserListSample} download="UserListSample.csv">
          Click here
        </a>
      )
    }
    

    Yor bundler should automaticaly bundle the file and adjust the href.

    2 Place the file in the public folder

    Given the snippet:

     <a href="/assets/UserListSample.csv" download="UserListSample.csv">
        Click here
     </a>
    

    I conclude you should put the file in public/assets/UserListSample.csv; bundlers put everything from the public folder into the package as-is, so it should be available for download after you run the app. You need to put the right path in the code yourself.

    3 If above doesn’t work

    It’s probably bundler’s fault. Try building the app (probably npm run build) and investigate the contents of the built package – see if the file is there somewhere. If it’s not then it means it’s not bundled properly. Search for UserListSample in other files to find that anchor you made – see what the path is – does it actually point to the file?

    You can also just share more code, including package.json and other files related to how you run your app. The CodeSandbox is a great tool for this (even if the sandbox might have some limitations disallowing to actually download files, a Proof of Concept can still be made).

    Login or Signup to reply.
  2. Always try to place the assets in the app_name/static/data folder

    <a  href={ window.location.origin+'/root_folder/static/data/example.csv' }
                      download={'download.csv'}
                      target="_blank"
                    >
                      Sample CSV
                    </a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search