如何在 NextJS 上请求下载文件的权限?

Mig*_*l V 5 download node.js express reactjs next.js

我有以下端点:

baseurl.com/api/v1/datasheet/format

访问此网址将下载基于数据表的特定信息。例如,在 Express 中,如果 format = json,我将返回此方法:

const generateJSON = (res, data) => {
    res.header('Content-Type', 'application/json');
    res.attachment('example.json');
    return res.send(data);
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但它会自动将文件下载为“example.json”,而不询问用户是否允许下载该文件

我的目的是在我的前端有一个按钮(使用 NextJS),它会询问用户是否要下载文件(经典下载或取消下载提示),然后打开文件资源管理器等。

我怎样才能做到这一点?这是来自后端还是前端的东西?

Ram*_*kay 3

用于Content-disposition: attachment; filename=example.json触发“另存为”对话框。

const generateJSON = (res, data) => {
    res.header('Content-Type', 'application/json');
    res.header('Content-disposition', 'attachment');
    res.attachment('example.json');
    return res.send(data);
}


Run Code Online (Sandbox Code Playgroud)

HTTP 上下文中的第一个参数是内联(默认值,表示它可以显示在网页内,或作为网页)或附件(表示应该下载它;大多数浏览器都会显示“另存为”对话框,预填充以及文件名参数的值(如果存在)。

通过https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#:~:text=The%20first%20parameter,parameters%20if%20present)。