34

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

1 Answer 1

39

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.