It is possible to create a file upload api in next.js? (using /api directory) Or I must use an external third party service online? Can't find any example online. Thanks
You can use this parameter to set metadata values to a collection already assigned to any parent folder. The rules are the same as those applied to the set metadata values REST API. Use Content-Type: application/json to describe this information as a JSON object. File to upload.
Now that we have updated our Next. js API route we can add the Multer middleware library to next-connect to handle that file upload for us.
You can upload files with Next.js API routes.
API handler
export default (req, res) => {
// req.body contains a content of an uploaded file + headers
}
req.body
is a string
that contains related HTTP headers in the beginning like
------WebKitFormBoundarydj2uhBXPZtD3nte3
Content-Disposition: form-data; name="your_input_name"; filename="your_file_name.json"
Content-Type: application/json
your file content is here!
So, you would need to take out the content from it. Probably there are some packages that can do it.
Alternatively, you can parse the request with a third-party package.
API handler
import { IncomingForm } from 'formidable'
// you might want to use regular 'fs' and not a promise one
import { promises as fs } from 'fs'
// first we need to disable the default body parser
export const config = {
api: {
bodyParser: false,
}
};
export default async (req, res) => {
// parse form with a Promise wrapper
const data = await new Promise((resolve, reject) => {
const form = new IncomingForm()
form.parse(req, (err, fields, files) => {
if (err) return reject(err)
resolve({ fields, files })
})
})
// read file from the temporary path
const contents = await fs.readFile(data?.files?.nameOfTheInput.path, {
encoding: 'utf8',
})
// contents is a string with the content of uploaded file, so you can read it or store
}
Code in the examples above for the illustration purpose only. At least need to wrap it in try catch
statement with proper error handling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With