Node - multer - 文件上传问题

时间:2017-05-20 01:59:19

标签: node.js mongodb express multer

我正在尝试使用multer进行文件上传。上传完成,但问题是我只想上传.avi文件,任何文件都被接受和上传。 我已经使用fileFilter设置了multer配置,但似乎它没有工作或被忽略。

这是我的代码:

const mongoose = require('mongoose');
const multer = require('multer');
const uuidV4 = require('uuid/v4');
const Video = require('../models/videoModel');



var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads')
    },


    filename: function (req, file, cb) {
        const newName = uuidV4(); 
        const extension = file.mimetype.split('/')[1];
        cb(null, newName +`.${extension}`)

  },

    fileFilter: function(req, file, cb){

        if(file.mimetype !== 'video/avi'){
          return cb(null, false, new Error('goes wrong on the mimetype'));
        }
        cb(null, true);
    }
})

var upload = multer({ storage: storage });
exports.uploadVideo = upload.single('video');

exports.CreateVideo =  async (req, res, next) => {
    const filePath = req.file.filename;
    const video =  await Video.create({title:req.body.title, path: filePath});
    console.log(video);
};

exports.Home = (req, res) =>{
    res.render('index');
};

1 个答案:

答案 0 :(得分:0)

fileFilter不是存储属性,而是较长的存储属性。

function fileFilter(req, file, cb) {

    console.log('file filter called')

    if (file.mimetype !== 'video/avi') {
        return cb(null, false, new Error('goes wrong on the mimetype'));
    }
    cb(null, true);
}

var upload = multer({ storage: storage, fileFilter: fileFilter });

希望它可以提供帮助。