'uploading images in public dir reactjs/nextjs

I've been trying to upload images in the /public directory this code is working fine locally (Windows OS)

import getConfig from "next/config";
import fs from "fs";
const address=path.join(getConfig().serverRuntimeConfig.PROJECT_ROOT, `/public/uploads/users/${username}`);
if (!fs.existsSync(address)) {
  fs.mkdirSync(address, { recursive: true });
}

I'm using multer for file uploading from client-side.

The above code is working fine on window os locally but in after deployment at vercel it throws the error:

2022-03-21T16:05:16.872Z 693e7f44-12d9-4f4e-90cf-f030a299f918 ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"Error: ENOENT: no such file or directory, mkdir '/vercel/path0/public/uploads/users/saif'","reason":{"errorType":"Error","errorMessage":"ENOENT: no such file or directory, mkdir '/vercel/path0/public/uploads/users/saif'","code":"ENOENT","errno":-2,"syscall":"mkdir","path":"/vercel/path0/public/uploads/users/saif","stack":["Error: ENOENT: no such file or directory, mkdir '/vercel/path0/public/uploads/users/saif'"," at Object.mkdirSync (fs.js:1013:3)"," at DiskStorage.destination [as getDestination] (/var/task/.next/server/pages/api/User/index.js:155:55)"," at processTicksAndRejections (internal/process/task_queues.js:95:5)","
at runNextTicks (internal/process/task_queues.js:64:3)"," at processImmediate (internal/timers.js:437:9)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: Error: ENOENT: no such file or directory, mkdir '/vercel/path0/public/uploads/users/saif'"," at process. (/var/runtime/index.js:35:15)"," at process.emit (events.js:412:35)"," at processPromiseRejections (internal/process/promises.js:245:33)"," at processTicksAndRejections (internal/process/task_queues.js:96:32)","
at runNextTicks (internal/process/task_queues.js:64:3)"," at processImmediate (internal/timers.js:437:9)"]} Unknown application error occurred



Solution 1:[1]

Vercel as a platform does not allow persistent file storage as these are serverless functions, they encourage uploads to a bucket like s3 -

https://vercel.com/docs/concepts/solutions/file-storage

  • Create a Serverless Function to return a presigned URL.
  • From the front-end, call your Serverless Function to get the presigned POST URL.
  • Allow the user to upload a file on the front-end. Forward the
  • file to the POST URL.

Note: here the presigned url is a s3 location that you are creating as a location.

They also post multiple examples by using different examples using s3 or Google storage bucket.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ramakay