在 next.js 中创建上传文件 api [英] Create upload files api in next.js

查看:77
本文介绍了在 next.js 中创建上传文件 api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

You can upload files with Next.js API routes.

API 处理程序

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

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

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 处理程序

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 语句中并进行适当的错误处理.

Code in the examples above for the illustration purpose only. At least need to wrap it in try catch statement with proper error handling.

这篇关于在 next.js 中创建上传文件 api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆