穆特 |不断收到““路径”参数必须是字符串类型。收到的类型号“

时间:2021-06-16 14:42:23

标签: node.js mongodb file mongoose multer

我正在尝试弄清楚如何使用 Multer 将视频从磁盘存储上传到 MongoDB,但我不断收到““路径”参数必须是字符串类型。接收到的类型编号”。

如果有人能帮助我找到正确的方向,我将不胜感激!

存储和存储上传

varchar         
----------------
0000010011010010

发布路线

const uploadStorage = multer.diskStorage({
    destination: (req, file, cb)=> {
        cb(null, './uploads/')
    },
    filename: (req, file, cb)=> {
        cb(null, Date.now(), + ' - ' + file.originalname)
    }
})

const storageUpload = multer({
    storage: uploadStorage
})

MongoDB 架构

app.post('/upload', storageUpload.single('videoUpload'), (req, res) => {
    const newVideoUpload = new uploadMongo({
        video: {
            data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
            contentType: 'video/mp4'
        }
    })

    newVideoUpload.save((err, data)=> {
        if(err) {
            throw err
        } else {
            res.redirect('/')
        }
    })
})

html 页面

const mongoose = require('mongoose')

const uploadSchema = mongoose.Schema({
    video: {
        data: Buffer,
        contentType: String
    }
}, {timestamps: true})

const uploadModel = mongoose.model('video', uploadSchema)
module.exports = uploadModel;

错误

<html>
    <head>
        <title><%= title %></title>
    </head>
    <body>
        <h3>Upload a video</h3>
        <form action="/upload" method="POST" enctype="multipart/form-data">
            <input type="file" name="videoUpload">
            <button type="submit">Upload</button>
        </form>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

错误来自这里:

<块引用>

cb(null, Date.now(), + ' - ' + file.originalname)

额外的 , 导致 Date.now() 作为文件名被传递而没有字符串运算符。 Date.now() 返回一个数字。

试试:

cb(null, String(Date.now()), + ' - ' + file.originalname)

cb(null, Date.now() + ' - ' + file.originalname)