Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create upload files api in next.js

Tags:

next.js

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

like image 487
user3343396 Avatar asked Feb 29 '20 13:02

user3343396


People also ask

Can we upload file using REST API?

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.

Can I use multer in next JS?

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.


1 Answers

You can upload files with Next.js API routes.

Example with default Next.js body parse

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.

Example with formidable

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.

like image 194
Nikolai Kiselev Avatar answered Sep 25 '22 06:09

Nikolai Kiselev