[英]React and Axios download a file from Node JS server
我正在嘗試從 Node JS 和 Express 服務器下載 React 中的文件。 在服務器中,我創建了一個端點,當我在瀏覽器中導航時,該端點會顯示下載彈出窗口。
router.get("/getfile", (req, res) => {
res.download("public/FILE.pdf");
});
但是我如何觸發這個瀏覽器彈出窗口 window 以使用 React 和 Axios 將文件保存在用戶自己的文件系統中?
donwloadFile = () => {
axios.get("localhost:3030/getfile").then(function (response) {});
};
您必須使用以下命令以反應方式安裝“js-file-download”庫
npm install --save js-file-download
然后將react文件中的代碼改成如下:
import download from 'js-file-download';
downloadFile = () => {
axios.get("localhost:3030/getfile")
.then(resp => {
download(resp.data, fileName);
});
}
服務器端的代碼如下:
router.get("/getfile", (req, res) => {
FileLocation ="public/FILE.pdf"
file="File.pdf"
res.download(fileLocation, file, (err) => {
if (err) console.log(err);
});
});
我對這個答案的參考是在這個鏈接中。
這對我有用。我希望它對你有用。
在發送文件之前,您必須輸入content type header
。
索引.js
router.get('/caderno1', (req, res) => {
res.contentType("application/pdf");
res.status(200).sendFile(__dirname + '/cadernos/CADERNO1.pdf');
});
當我實現這個時,我使用了方法sendFile
。 我不知道它是否適用於res.download
。
這是我簡化的文件樹結構:
├── cadernos
| ├── caderno1.pdf
| └── caderno2.pdf
├── _server
| └── index.js
├── app.js
└── package.json
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.