【问题标题】:The \"path\" argument must be of type string or an instance of Buffer or URL. Received undefined\"path\" 参数必须是字符串类型或 Buffer 或 URL 的实例。收到未定义
【发布时间】:2021-06-10 02:42:00
【问题描述】:

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

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]
  }
}

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

【问题讨论】:

    标签: node.js file-upload cloudinary


    【解决方案1】:

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

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

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

    file[""].tempFilePath
    

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 2021-08-18
      • 2021-08-07
      • 2022-11-11
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2021-06-24
      • 2022-01-21
      相关资源
      最近更新 更多