如何在Next.js中实现文件下载按钮?(窗口未定义)

3

我知道在React组件挂载之前,'window'或'document'对象是不可识别的。

我正在尝试制作一个下载按钮,该按钮从后端服务器接收处理过的Excel文件。在使用React之前,我通常会这样实现...

 <button onclick="download()">Download</button>
    <script>
        function download() {
            const URL = 'http://dynamic-link.com/sample.xlsx'
            window.location.href = URL
        }
    </script>

然而在Next.js或React中,window对象无法被识别,因此我不得不采取其他方式。下载URL是动态的,因此我不会使用next.config.js

pages/index.tsx

//...
const handleDownloadExcel = () => {
    router.push('/download')
  }
//...
return(
//...
      <button onClick={() => handleDownloadExcel()}>Download!</button>
//...

pages/download.tsx

import { useEffect } from 'react'
import { useRouter } from 'next/router'
const DownloadPage = () => {
    const router = useRouter();
    useEffect(() => {
        //I will pass this URL variable by props later on.
        const URL = 'http://dynamic-url.com/sample.xlsx'
        window.location.href = URL;
        router.push('/')
    }, [])

    return (
        <>
        </>
    )
}

export default DownloadPage;

现在我已经成功从服务器上下载了一个文件,但似乎不太对劲。有其他方法可以做到这一点吗?
3个回答

2
你可以像这样在Next.js中使用window对象:
    <script>
        function download() {
            const URL = 'http://dynamic-link.com/sample.xlsx'
            if (typeof window !== "undefined"){
              window.location.href = URL
            }
        }
    </script>

1
使用file-saver包来下载我们的文件。
安装它,运行如下命令:
npm i file-saver

然后我们可以通过以下方式调用该包中的saveAs函数:

import React from "react";
import { saveAs } from "file-saver";

export default function App() {
  const saveFile = () => {
    saveAs(
      "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
      "example.pdf"
    );
  };
  return (
    <div>
      <button onClick={saveFile}>download</button>
    </div>
  );
}

第一个参数是要下载的URL,第二个参数是已下载文件的文件名。

0

感谢您提供的脚本,它解决了这个问题。我还发现在NextJS中将文件复制到 /public/download/ 目录下可以防止出现 - HEAD https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf net::ERR_FAILED 200 错误。

将 "example.pdf" 更改为预期的文件名也可以防止默认情况下下载文件被命名为“download.pdf”。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接