1

I have MERN application and I want to download a CSV file on button click. I implemented everything but when I click the button there is no download in browser.

Axios call

const handleDownloadCsv = async () => {
    try {
        await axios.get('http://localhost:2000/users/admin-panel/csv');
    } catch (error) {
        console.log(error);
    }
};

NodeJs controller

export const admin_panel_csv = async (req,res) => {
try {

    let __dirname = res.locals.__dirname;

    const myReadStream = fs.createReadStream(__dirname + '/documents/admin_csv.csv');

    //myReadStream.pipe(res);
    res.download(__dirname + '/documents/admin_csv.csv')

} catch (error) {
    console.log('Error csv: ',error.message);
    res.status(400).json({msg:error.message});
  }
 }

I've tried both createReadStream(with pipe) and res.download(path to file) but non of them seams to work. I am not getting any errors when making this api call through axios. Is there some way to accomplish this without using React libraries.

1
  • There doesn't appear to be a reason for admin_panel_csv to be async. That will just return a promise. Commented Nov 10, 2021 at 0:18

2 Answers 2

2

There is no download prompt in the browser since you are initiating the download via axios and not through the browser (e.g., through a <form> POST or an <a> click).

Change the back-end code back to res.download and on the front-end, initiate the download through an <a> click:

const handleDownloadCsv = () => {
  const tempLink = document.createElement('a')
  tempLink.href = 'http://localhost:2000/users/admin-panel/csv'
  tempLink.click()
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think that you should use js-file-download in React and just :

const FileDownload = require('js-file-download');
Axios.get(API_URL + "download")
.then((response) => {
    FileDownload(response.data, 'file.txt');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.