【问题标题】:Download file in react, sent by express在反应中下载文件,通过快递发送
【发布时间】:2020-08-26 16:24:16
【问题描述】:

到目前为止,我在 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 中,并像这样处理请求:

index.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 文件?我错过了什么?

【问题讨论】:

    标签: javascript node.js reactjs express


    【解决方案1】:

    您必须使用 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);
        })
    

    【讨论】:

    • 就像我提到的,锚标签变体似乎不起作用。 const url = window.URL.createObjectURL(blob); 创建 Unhandled Rejection (TypeError): Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
    • 您从 API 调用中得到什么响应?如果邮递员能够下载文件,你检查过邮递员吗?
    • Postman 确实在body 下显示了相应的 JSON,我认为这意味着它可以与 Postman 一起使用。它还将文件和数据的键值作为 application/x-www-form-urlencoded 发送,但是当我在前端应用程序中将内容类型设置为相同时,后端不会收到任何数据。如果邮递员收到可下载的文件,它是否应该有某种不同的响应?
    • 你的问题是,下载文件......你为什么收到 JSON 而不是邮递员响应中的编码 blob 数据。我错过了什么吗?
    • 我不确定你的问题是什么。我应该收到什么?根据上述代码,我如何发送除 JSON 之外的任何内容?你问的问题和我问的一样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2012-05-11
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多