[英]How to store files in production in Next.js?
我有一个要部署的文件交换 Next.js 应用程序。 在开发过程中,无论何时删除文件,应用程序都会将文件存储在根公共文件夹中,当下载文件时,应用程序也会使用带有uploads/{filename}
href 属性的<a>
标签从那里获取文件。 这一切在开发中都运行良好,但在生产中却行不通。
我知道每当npm run build
时,Next.js 都会从公用文件夹中获取文件,并且不会提供在运行时添加到那里的文件。
问题是,除了 AWS S3 等第三方服务之外,Next.js 中是否还有任何持久文件存储方式?
Next.js 允许在构建时存储文件,但不允许在运行时存储。 Next.js 将无法满足您的文件上传要求。 AWS S3 是这里的最佳选择。
node
运行时的next
是NodeJS ,因此如果您的云提供商允许创建永久磁盘并将其安装到您的项目,那么您可以这样做:
pages/api/saveFile.ts
:import { writeFileSync } from 'fs';
import { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { path = null } = req.query;
if (!path) {
res.status(400).json({ name: 'no path provided' })
} else {
// your file content here
const content = Date.now().toString();
writeFileSync(`/tmp/${path}.txt`, content);
res.json({
path,
content
})
}
}
/tmp
几乎适用于每个云提供商(包括 Vercel 本身),但这些文件将在下一次部署时丢失; 相反,您应该使用已安装的磁盘路径
pages/api/readFile.ts
import { readFileSync } from 'fs';
import { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { path = '' } = req.query;
if (!path) {
res.status(400).json({ name: 'wrong' })
} else {
res.send(readFileSync(`/tmp/${path}`));
}
}
实时运行示例:
fetch('https://eaglesdoc.vercel.app/api/writefile?path=test').then(res => res.text()).then(res => console.log(res)).then( () => fetch('https://eaglesdoc.vercel.app/api/readfile?path=test')).then(res => res.text()).then(res => console.log(res))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.