在反应中下载文件,通过快递发送



到目前为止,我在SO上读到的其他解决方案都没有奏效,所以请耐心等待。

我在 React 中有一个前端,用户在其中向后端发送文件下载请求以及一些变量:

const data = text.value;
fetch("http://localhost:4000/dl", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data,
file: filetypes.selected,
}),
}).then((res) => {
...???...
});

data变量是一些 JSON,如下所示:{"arrowParens": "always"}

file变量包含要下载的文件名:.prettierrc

我的后端在 NodeJs/express 中,并像这样处理请求:

索引.ts:

app.use("/dl", getFile);

getFile.ts:

import appRoot from "app-root-path";
const index = async (req: Request, res: Response) => {
const { data, file } = req.body;
// download file if folder exists
if (fs.existsSync(`${appRoot}/tmp/${file}`)) {
res.sendFile(
".prettierrc",
{
dotfiles: "allow",
headers: {
"Content-Type": "json",
},
root: path.join(__dirname, "../tmp"),
}
);
}
};

我从服务器得到正确的响应:POST /dl 200 11.878 ms - 55但文件没有下载,所以我想我必须有一些额外的代码。我读过另一篇文章,其中 OP 创建了一个锚标记,并将href设置为 blob URL,但这似乎不起作用,因为响应没有向我显示 URL。我不得不选择POST请求,因为我必须发送那些文件确定变量。不确定方法在这里是否有区别。

如何让浏览器提示下载我的.prettierrc文件?我错过了什么?

您必须使用 href 创建一个锚标记并触发点击。 像这样的东西


fetch("http://localhost:4000/dl", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data,
file: filetypes.selected,
}),
}).then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = id;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})

最新更新