简体   繁体   English

Next.js生产中如何存储文件?

[英]How to store files in production in Next.js?

I have a file exchange Next.js app that I would like to deploy.我有一个要部署的文件交换 Next.js 应用程序。 In development whenever file is dropped, the app stores the file in root public folder, and when the file is downloaded the app takes it from there as well using the <a> tag with href attribute of uploads/{filename} .在开发过程中,无论何时删除文件,应用程序都会将文件存储在根公共文件夹中,当下载文件时,应用程序也会使用带有uploads/{filename} href 属性的<a>标签从那里获取文件。 This all works pretty well in development, but not in production.这一切在开发中都运行良好,但在生产中却行不通。

I know that whenever npm run build is run, Next.js takes the files from public folder and the files added there at runtime will not be served.我知道每当npm run build时,Next.js 都会从公用文件夹中获取文件,并且不会提供在运行时添加到那里的文件。

The question is are there any ways of persistent file storage in Next.js apart from third party services like AWS S3?问题是,除了 AWS S3 等第三方服务之外,Next.js 中是否还有任何持久文件存储方式?

Next.js does allow file storage at buildtime, but not at runtime. Next.js 允许在构建时存储文件,但不允许在运行时存储。 Next.js will not be able to fulfill your file upload requirement. Next.js 将无法满足您的文件上传要求。 AWS S3 is the best option here. AWS S3 是这里的最佳选择。

next in node runtime is NodeJS , thus If your cloud provider allows create persistent disk and mount it to your project, then you can do it: node运行时的nextNodeJS ,因此如果您的云提供商允许创建永久磁盘并将其安装到您的项目,那么您可以这样做:

eg pages/api/saveFile.ts :例如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 works almost in every cloud provider (including Vercel itself), but those files will be lost on next deployment; /tmp几乎适用于每个云提供商(包括 Vercel 本身),但这些文件将在下一次部署时丢失; instead you should use your mounted disk path相反,您应该使用已安装的磁盘路径

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}`));
    }
}

Live running example:实时运行示例:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM