在我的 nextjs 应用程序中,我想添加一个用户单击它并下载 pdf 文件的按钮。我将pdf文件添加到
public/documents/
并将其导入并添加到link href
。但点击它后,即使生成的文件存在,它也会显示 404 页面,我可以在 Chrome 检查 > 源(在 _next 中)上观看它。我正在使用 webpack 文件加载器。
下一个配置:
const nextConfig = {
output: "standalone",
webpack: (config, options) => {
config.module.rules.push({
test: /\.(png|gif|mp4|pdf)$/i,
use: [
{
loader: "file-loader",
options: {
name: "[name].[ext]",
},
},
],
});
return config;
},
};
我的页面代码:
import LeaderInstructions from "@documents/leaders-instructions.pdf";
...
//other codes
...
<a
href={LeaderInstructions}
target="_blank"
>
有人知道我该怎么办吗?
您可以尝试使用公共目录中的相对路径引用它,而不是直接导入 PDF。
<a
href="/documents/leaders-instructions.pdf"
target="_blank"
>
Download Leader Instructions PDF
</a>
如果您想继续使用导入的PDF,您可以尝试如下操作:
import { useRouter } from 'next/router';
const router = useRouter();
const downloadPDF = () => {
router.push('/documents/leaders-instructions.pdf');
}
<button onClick={downloadPDF}>Download PDF</button>