nextjs项目上传文件部署到vercel报错

1/1/2025 nextjsvercel

nextjs项目上传文件到当前目录文件夹下面,本地运行正常,部署到vercel报错,错误信息如下:

Error: EROFS: read-only file system

这个错误通常是由于在服务器端尝试写入只读文件系统而引起的。

原代码:

import fs from 'fs';
import path from 'path';

export const config = {
  api: {
    bodyParser: {
      sizeLimit: '10mb', // 设置上传文件大小限制
    },
  },
};

export default function handler(req, res) {
  if (req.method === 'POST') {
    const { file } = req.body;

    // 这里上传到当前项目根目录uploads文件夹中, 本地运行正常,部署到vercel报错
    const filePath = path.join(process.cwd(), 'uploads', file.name);
    fs.writeFileSync(filePath, Buffer.from(file.data, 'base64'));

    res.status(200).json({ message: 'File uploaded successfully!' });
  } else {
    res.status(405).json({ message: 'Method not allowed' });
  }
}

解决思路:如果你只需要临时存储数据,可以使用 /tmp 目录。这个目录通常是临时的,会在重启时清空

更改为如下代码:

import fs from 'fs';
import path from 'path';
const tmpPath = require('os').tmpdir()

export const config = {
  api: {
    bodyParser: {
      sizeLimit: '10mb', // 设置上传文件大小限制
    },
  },
};

export default function handler(req, res) {
  if (req.method === 'POST') {
    const { file } = req.body;

    const filePath = path.resolve(tmpPath, file.name);
    fs.writeFileSync(filePath, Buffer.from(file.data, 'base64'));

    res.status(200).json({ message: 'File uploaded successfully!' });
  } else {
    res.status(405).json({ message: 'Method not allowed' });
  }
}

参考资料:

NeteaseCloudMusicApi项目解决代码 (opens new window)

What is this error: EROFS: read-only file system, open? And how do I fix it · vercel/community · Discussion #314 · GitHub (opens new window)