我有 MERN 應用程式,我想通過單擊按鈕下載 CSV 檔案。我實作了所有內容,但是當我單擊按鈕時,瀏覽器中沒有下載。
axios 呼叫
const handleDownloadCsv = async () => {
try {
await axios.get('http://localhost:2000/users/admin-panel/csv');
} catch (error) {
console.log(error);
}
};
NodeJs 控制器
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});
}
}
我已經嘗試了 createReadStream(with pipe) 和 res.download(path to file) 但它們都沒有作業。通過 axios 進行此 api 呼叫時,我沒有收到任何錯誤。有什么方法可以在不使用 React 庫的情況下實作這一點。
uj5u.com熱心網友回復:
我認為你應該在 React 中使用 js-file-download 并且只是:
const FileDownload = require('js-file-download');
Axios.get(API_URL "download")
.then((response) => {
FileDownload(response.data, 'file.txt');
});
uj5u.com熱心網友回復:
瀏覽器中沒有下載提示,因為您是通過axios而不是通過瀏覽器(例如,通過<form>POST 或<a>單擊)啟動下載。
將后端代碼改回res.download并在前端,通過<a>單擊啟動下載:
const handleDownloadCsv = () => {
const tempLink = document.createElement('a')
tempLink.href = 'http://localhost:2000/users/admin-panel/csv'
tempLink.click()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/354957.html
