首页 > 解决方案 > 上传到 S3 的节点 Js 错误:TypeError [ERR_INVALID_ARG_TYPE]

问题描述

我正在尝试将图像上传到我的 amazon s3 存储桶,但我不断收到错误消息

TypeError [ERR_INVALID_ARG_TYPE]:第一个参数必须是 string、Buffer、ArrayBuffer、Array 或 Array-like Object 类型之一。

所以基本上我知道我必须将其更改为缓冲区,经过一番搜索后,我尝试了一些解决方案,但没有一个有效,有人可以帮我指出我出了什么问题吗?

  const s3Client = s3.s3Client;
  const params = s3.uploadParams;

  //const fileContent = fs.readFileSync(req.file); <-- tried this and still gave the same error
  var fileContent = Buffer.from(req.file, 'base64')

  params.Key = req.file.filename
  params.Body = fileContent

  console.log(req.file)

  s3Client.upload(params, (err, data) => {
    if (err) {
      res.status(500).json({error:"Error -> " + err});
    }
    res.json({message: 'File uploaded successfully! -> keyname = ' + req.file.originalname});
  });

这是图像本身,也许我转换错误?详细信息取自 req.file 控制台日志

{
  fieldname: 'image',
  originalname: 'Kimmi.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './images/',
  filename: 'c6b46e20-4efc-11ea-8b6a-1b4d698f6335.jpeg',
  path: 'images\\c6b46e20-4efc-11ea-8b6a-1b4d698f6335.jpeg',
  size: 35920
}

标签: node.jsamazon-s3

解决方案


我不太确定,但我认为您正在使用 multer ?如果您使用 multer,您基本上可以使用 req.file.buffer。

如果图像是大流示例,我的建议是使用流而不是缓冲区


推荐阅读