Skip to content
Advertisement

How can i upload file using formidable with nextjs on vercel

api/upload.js

import formidable from 'formidable';

export const config = {
  api: {
    bodyParser: false,
  },
};

export default async (req, res) => {
  const form = new formidable.IncomingForm();
  form.uploadDir = "./";
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    console.log(err, fields, files);
    res.send(err || "DONE")
  });
};

api/get.js

export default async (_, res) => {
    const fs = require('fs');
    fs.readdir("./", (err, files) => {
        console.log(err)
        res.send(err || files)
    });
};

Everything is working fine at localhost but it’s not working when i deploy it on vercel.

Function log from vercel dashboard

[POST] /api/upload

2021-02-21T12:47:11.662Z    f7bb8a02-2244-4d27-8a55-9e00a43b307b    ERROR   Uncaught Exception  {"errorType":"Error","errorMessage":"EROFS: read-only file system, open 'upload_2dd906bdebc97a1d63a371c9207b84be.png'","code":"EROFS","errno":-30,"syscall":"open","path":"upload_2dd906bdebc97a1d63a371c9207b84be.png","stack":["Error: EROFS: read-only file system, open 'upload_2dd906bdebc97a1d63a371c9207b84be.png'"]}
Unknown application error occurred

Advertisement

Answer

if it works on localhost, it’s because the application mode on localhost is dev, and if in vercel the application mode is production so it only relies on the .next folder.

if you really want to give it a try, try putting the upload file in the .next/static directory, but it still won’t work, with the caveat that the files in vercel are read-only.

path.resolve('.next','static');

i have the same problem, and it seems that i can’t really add files in vercel (put upload files to vercel server).

the only way is to create another server to place the uploaded files. or deploy your application to another server that supports this.

or you can also use the recommendations from vercel, please check at https://vercel.com/docs/solutions/file-storage

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement