skip to Main Content

I have a csv file in my directory that I want to trigger a direct download for upon clicking a download button.

I used the file-saver library and a fetch request to handle everything.

here is the function:


  const handleDownload = () => {
    fetch('public/data/COW2021001887-I589Data.csv', {
      headers: {
        'Content-Type': 'text/csv'
      }
    })
      .then(response => response.blob())
      .then(blob => saveAs(blob, 'file.csv'))
      .catch(error => console.error(error));
  };

But when I click the button, i get an excel spreadsheet that only has an HTML template with it..

attached is a picture of the path, in case that’s the issue because it’s theonly thing I can think. Of course i imported save as from the file-saver library and this function is the handler for the button.

Any advice would be appreciated. I’ve tried triggering hte download a few different ways but always end up with an html template document (also pictured)

the CSV with the html template
the paths of the files i’m working on Render landing page near the bottom, the file is in public/data

2

Answers


  1. Have you tried using the library to save the URL directly?

    const FileSaver = require('file-saver');
    
    const handleDownload = () => {
      FileSaver.saveAs("public/data/COW2021001887-I589Data.csv", "file.csv");
    };
    

    Also, are you using an older version of file-saver? I’m not seeing the .blob() syntax in the documentation, but only the new Blob syntax:

    var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
    
    Login or Signup to reply.
  2. instead of response.blob(), try using the new operator like this:

      const handleDownload = () => {
        fetch('public/data/COW2021001887-I589Data.csv', {
          headers: {
            'Content-Type': 'text/csv'
          }
        })
          .then(response => {
              // double check the response object is what you want here
              const blob = new Blob([response], {type: "text/csv"});
              FileSaver.saveAs("file.csv");
          })
          .catch(error => console.error(error));
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search