I am getting this error when using Formidable with NextJS 13:
Critical dependency: the request of a dependency is an expression // error
Import trace for requested module:
./node_modules/formidable/src/Formidable.js
./node_modules/formidable/src/index.js
./app/api/rest/file/route.ts
error - Error: Cannot find module 'C:\Users\jacob\Documents\GitHub\pim-nextjs-ts\yakpim\.next\server\app\api\rest\file\plugins\octetstream.js'
This is the code block:
export async function POST(request: NextApiRequest, response: NextApiResponse) {
console.log("success"); // this works
const form = formidable({ multiples: true }); // this triggers the error
I have tried yarn update formidable as well as ''yarn remove'' and ''yarn add'' again. No fix on the error.
In the node_modules > formidable folder I can see the plugin is added and used but this causes an error.
Wondering if anyone else has encountered and how you managed to resolve?
Thanks!
yarn update - no fix
yarn remove & yarn install - no fix
Since formidable couldn't handle it, I imported the file directly from formdata and saved it.
In the request's formData, we converted the File object to a Buffer and stored it.
Below is an example of how this is done to save an image.
export const POST = async(req: NextRequest) => {
const f:any = await req.formData();
const obj = Object.fromEntries(f);
Object.entries(obj).forEach( async([k, v]) => {
if( !!v.type ) { // If it's a file, values like image/png are passed over.
const b = await v.arrayBuffer();
const buff = Buffer.from(b);
fs.writeFileSync(`./public/${k}`, buff);
}
});
}
If you have a fixed key value without having to convert to Object.fromEntries, you can use the
const fileObject = f.get("filename");
const b = await fileObject.arrayBuffer();
const buff = Buffer.from(b);