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.
CodePudding user response:
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');
});
CodePudding user response:
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()
}