如何使用 formdata 将图像文件发送到 React/Next js api? [英] How to send an image file using formdata to React/Next js api?

查看:91
本文介绍了如何使用 formdata 将图像文件发送到 React/Next js api?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在下一个 js 应用程序中将文件发送到 api.图片将上传到 cloudinary:

I am trying to send a file to api in a next js app. The image will be uploaded to cloudinary:

函数调用api为:

  async uploadButtonClicked(imageUpload) {
      const formData = new FormData();
      //formData.append('test', "testing");
      formData.append('postPic', imageUpload.files[0]);
      const res = await fetch('/api/hello', {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data',
          'Accept': 'application/json'
        },
        body: formData,
      })

console.log(imageUpload.files[0]) 前端给了我下面的值,看起来不错.

console.log(imageUpload.files[0]) in front end gives me the values below and looks good.

在 api 中,

export default (upload.single('postPic'), async (req, res) => {
  console.log(req.body)

当我使用时,上面是undefined

export const config = {
  api: {
    bodyParser: false,
  },
};

当我删除 bodyParser 设置(bodyParser 为 true)时,数据是一个对上传没有用的流.我收到上传错误,如下所示:

When I remove the bodyParser setting (bodyParser is true), the data is as a stream which is not useful for upload. I get a upload error as shown below:

如果正文以下面的格式到达 api,Cloudinary 将上传:

Cloudinary will upload if the body reaches the api in this format below:

应该改变什么才能让主体(基本上是一个图像文件)以正确的格式到达 api,如上所示?

What should be changed to get the body (which is basically an image file) to reach the api in the proper format as shown above?

我认为这个问题也可以问:为什么在使用 bodyParser: falsereq.body undefined ?

I think the question can also be asked as: Why is the req.body undefined when using bodyParser: false ?

推荐答案

我遇到了同样的错误,但 Formidable 对我有用.尝试先将图像放入表单数据中.

I ran into the same error but Formidable worked for me. Try putting the image into Form Data first.

来自客户:

export const uploadImage = async (image) => {

    const formData = new FormData();
    formData.append('image', image);
    const response = await axios.post('/api/v1/image', formData);
    return response.data;
}

以下是服务器 API:/api/v1/image

And below is on server API : /api/v1/image

import formidable from 'formidable';


export const config = {
  api: {
    bodyParser: false,
  },
}

export default async (req, res) => {
  const form = new formidable.IncomingForm();
  form.uploadDir = "./";
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    console.log(err, fields, files);
  });
};

这篇关于如何使用 formdata 将图像文件发送到 React/Next js api?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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