\"path\" 参数必须是字符串类型或 Buffer 或 URL 的实例。收到未定义

时间:2021-03-12 03:37:08

标签: node.js file-upload cloudinary

美好的一天,我是编码新手,遇到一个我自己无法解决的奇怪问题,请参阅下面的代码。
我在一个电子商务网站上工作,我编写了与视频中显示的代码相同的代码,但仍然面临这个问题

const router = require('express').Router()
const cloudinary = require('cloudinary')
const auth = require('../middleware/auth')
const authAdmin = require('../middleware/authAdmin')
const fs = require('fs')


// we will upload image on cloudinary
cloudinary.config({
    cloud_name: process.env.CLOUD_NAME,
    api_key: process.env.CLOUD_API_KEY,
    api_secret: process.env.CLOUD_API_SECRET
})

// Upload image only admin can use
router.post('/upload',auth , authAdmin, (req, res) =>{
    try {
        if(!req.files || Object.keys(req.files).length === 0)
            return res.status(400).json({msg: 'No files were uploaded.'})
        
        const file = req.files;
       console.log(file)
        if(file.size > 1024*1024) {
            removeTmp(file.tempFilePath)
            return res.status(400).json({msg: "Size too large"})
        }

        if(file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png'){
            removeTmp(file.tempFilePath)
            return res.status(400).json({msg: "File format is incorrect."})
        }

        cloudinary.v2.uploader.upload(file.tempFilePath, {folder: "test"}, async(err, result)=>{
            if(err) throw err;

            removeTmp(file.tempFilePath)

            res.json({public_id: result.public_id, url: result.secure_url})
        })


    } catch (err) {
        return res.status(500).json({msg: err.message})
    }
})

const removeTmp = (path) =>{
    fs.unlink(path, err=>{
        if(err) throw err;
    })
}

module.exports = router

我收到一个错误:

{
    "msg": "The \"path\" argument must be of type string or an instance of Buffer or URL. Received undefined"
}

我在第 21 行使用控制台:

{
  '': {
    name: 'adidas.jpg',
    data: <Buffer >,
    size: 12302,
    encoding: '7bit',
    tempFilePath: 'C:\\Users\\back-end\\tmp\\tmp-1-1615519087170',
    truncated: false,
    mimetype: 'image/jpeg',
    md5: '262073b93fdb5aa3f9dff6b5a010f2ed',
    mv: [Function: mv]
  }
}

我无法为我的错误找到解决方案,因为我是编码新手
感谢您的帮助

1 个答案:

答案 0 :(得分:0)

好像 file/req.files 是一个数组的数组。 file 的第一个元素的键是否等于空字符串 ('')?

{
  '': {
    ...
    tempFilePath: 'C:\\Users\\back-end\\tmp\\tmp-1-1615519087170',
    ...
  }
}

假设第一个键是空字符串,然后访问 tmpFilePath 将是:

file[""].tempFilePath