1 | initial version |
The process of uploading a file using NextJS and formidable involves the following steps:
Install both NextJS and formidable packages using npm command line interface.
Import the Formidable package using the require() function in the Node.js script.
Create a form in the frontend of the application where users can upload files.
Add an "onSubmit" event listener to the form that calls a function to handle the file upload.
In the handling function, extract the uploaded file from the form using formidable.
Save the file to a specified location using the Node's file system method.
Redirect the user to a success page or notify them of the successful upload.
Here's an example code snippet that demonstrates the process of uploading a file using NextJS and formidable:
import formidable from 'formidable';
import fs from 'fs';
export default function fileUpload(req, res) {
const form = new formidable.IncomingForm();
form.parse(req, (err, fields, files) => {
const oldPath = files.file.path;
const newPath = `./public/uploads/${files.file.name}`;
fs.rename(oldPath, newPath, err => {
if (err) throw err;
res.status(200).json({ message: 'File uploaded successfully!' });
})
})
}
In this example, we are creating an endpoint "fileUpload" that receives a file through a form and saves it to a "public/uploads" folder. The file is extracted from the form submitted using formidable package and renamed to the specified location using the Node's file system method. Finally, a success message is sent to the user through a JSON response.