Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 673
Rahul Avatar asked Sep 10 '25 05:09

Rahul


2 Answers

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

like image 169
Catur Wicaksono Avatar answered Sep 12 '25 19:09

Catur Wicaksono


You can make this work by making one small change in your code.

form.uploadDir = "/tmp";
like image 24
Anirudh Avatar answered Sep 12 '25 20:09

Anirudh