首页 > 解决方案 > 如何在 Express.js 中读取上传的文件

问题描述

我上传了一张在 Insomnia 上测试过的图片 失眠测试

这是我的图像应该上传到 Amazon S3 的代码

router.route('/picture').post((req, res) => {
    console.log(req.files) 
...

console.log(req.files) 返回:

  file: {
    name: '303b4ed5482b3a88140c79b1d7859dcf[1].png',
    data: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 01 00 00 00 01 00 08 06 00 00 00 5c 72 a8 66 00 00 20 00 49 44 41 54 78 9c ec bd 07 9b db 48 b2 ... 39048 more bytes>,    
    size: 39098,
    encoding: '7bit',
    tempFilePath: '',
    truncated: false,
    mimetype: 'image/png',
    md5: 'e8fef4ef43945e06e81d56c6b3c82053',
    mv: [Function: mv]
  }
}
...
    fs.readFile(req.files.file[0].data, (err, data) => {
        if (err) throw err;
        const params = {
            Bucket: 'name',
            Key: `profilepictures/${req.body.userid}`,
        };
        s3.upload(params, function(errs3, data) {
            if (errs3) throw errs3
            console.log(data)
        })
    })
})

我的观点是我如何阅读req.files.file[0].data,以便它可以识别为图像并上传到我的 S3 存储桶。

当我上传图片时,抛出了一个错误: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined

编辑: ( fs.readFile(req.files.file[0].data, (err, data) => {) 至 ( fs.readFile(req.files.file.data, (err, data) => {)

TypeError [ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes. Received <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 01 00 00 00 01 00 08 06 00 00 00 5c 72 a8 66 00 00 20 00 49 44 41 ...

标签: node.jsexpressfileamazon-s3

解决方案


推荐阅读