使用带有req.file的if语句进行单个文件上传

时间:2016-09-01 08:27:32

标签: javascript node.js mongodb if-statement multer

我有一个基本的网络应用程序,我希望用户能够在表单中注册图片上传,但如果他们当前没有要上传的图片我想自动设置默认图像已作为noimage.png存储在uploads文件夹中的本地存储,并作为用户的配置文件图像存储。这是我的试用但不起作用;

var multer = require('multer');


//var uploads = multer({dest: './uploads/'});

var storage = multer.diskStorage({
    destination: function (request, file, callback) {
        callback(null, './uploads');
    },
    filename: function (request, file, callback) {
        console.log(file);
        callback(null, file.fieldname)
    }
});
var upload = multer({ storage: storage });
router.post('/register', upload.single('profileimage'), function(req,res,next){

    `if(req.file.profileimage){
            console.log('uploading File...');

            // File Info
            var profileImageOriginalName = req.files.profileimage.originalname;
            var profileImageName = req.files.profileimage.name;

            var profileImageMime = req.files.profileimage.mimetype;
            var profileImagePath = req.files.profileimage.path;
            var profileImageExt = req.files.profileimage.extension;
            var profileImageSize = req.files.profileimage.size;
        } else {
            // Set a Default Image
            var profileImageName = 'noimage.png';
        }

我如何使用multer来处理这个问题?

1 个答案:

答案 0 :(得分:2)

如果您只有一个文件,则只需使用req.file,而不是req.file.<fieldname>。这意味着只使用req.file.originalnamereq.file.mimetype

访问所有文件信息