在 next.js 中创建上传文件 api

Create upload files api in next.js

可以在 next.js 中创建文件上传 api 吗? (使用 /api 目录) 或者我必须在线使用外部第三方服务? 在网上找不到任何例子。 谢谢

如果您使用的是自定义 Express 服务器,那么您应该了解如何为 Express 创建上传端点,而不是 NextJS。

如果您正在查看页面内新的 /api 目录,恐怕我没有那么多信息可以提供帮助。

您可以使用 Next.js API 路由上传文件。

默认示例 Next.js body 解析

API处理程序

export default (req, res) => {
  // req.body contains a content of an uploaded file + headers
}

req.body 是一个 string 开头包含相关的 HTTP headers 如

------WebKitFormBoundarydj2uhBXPZtD3nte3
Content-Disposition: form-data; name="your_input_name"; filename="your_file_name.json"
Content-Type: application/json
your file content is here!

因此,您需要从中取出内容。可能有一些软件包可以做到这一点。

或者,您可以使用 third-party 包解析请求。

示例formidable

API处理程序

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
}

以上示例中的代码仅供说明之用。至少需要将其包装在 try catch 语句中并进行适当的错误处理。