【问题标题】:Imgur upload api error always returning 400 with multer and form-data nodejsImgur上传api错误总是用multer和form-data nodejs返回400
【发布时间】:2021-06-06 00:26:04
【问题描述】:

我正在使用 react antd 上传图片。这是我处理上传请求的特快:

router.post('/upload-image', upload.any(), async function(req, res, next) {
    const file = req.files[0];
    const form = new FormData();
    form.append('image', file.buffer);
    form.append('type', 'file');

    const imgurInstance = new imgur({
        refreshToken: user.imgurRefreshToken,
        clientId: IMGUR_CLIENT_ID,
        clientSecret: IMGUR_CLIENT_SECRET
    });

    await imgurInstance.getAccessToken();
    const response = await imgurInstance.uploadImage(form);
    const data = await response.json();
});

这里记录了 req.files[0] 控制台:

{
  fieldname: 'file',
  originalname: 'headscratch.jpeg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 01 00 01 00 00 ff e1 00 42 45 78 69 66 00 00 4d 4d 00 2a 00 00 00 08 00 01 87 69 00 04 00 00 00 01 00 00 ... 13803 more bytes>,
  size: 13853
}

这是我使用 node-fetch 的 uploadImage 函数

uploadImage (form){
    const path = `/3/upload`;
    const headers = {
        'Authorization': `Bearer ${this.accessToken}`,
        ...form.getHeaders()
    };
    const options = {
        method: 'POST',
        body: form,
        headers
    };

    return fetch(`${this.BASE_API_URL}${path}`, options);
}

我总是从 imgur 获得 400 分,但他们没有提供任何详细信息。

{
  status: 400,
  success: false,
  data: { error: 'Bad Request', request: '/3/upload', method: 'POST' }
}

我尝试过使用 base64,只是使用 form-data 上传一个 url,我仍然收到 400 错误。有人对如何成功进行此通话有任何指导吗?谢谢。

【问题讨论】:

    标签: node.js multer form-data imgur


    【解决方案1】:

    我想我需要了解表单数据实际上在做什么。显然 form-data 不会作为文件发送,除非您将文件名与 {filename: ''} 作为选项包含在一起

    form.append('image', file.buffer, {filename: file.originalname});
    

    imgur 终于接受了我的请求,瞧。

    【讨论】:

      猜你喜欢
      • 2015-11-01
      • 2021-12-18
      • 2017-12-07
      • 2018-03-28
      • 2019-07-05
      • 2021-08-16
      • 1970-01-01
      • 2011-04-11
      • 2014-01-04
      相关资源
      最近更新 更多