如何在multer中的requst块中访问文件名

时间:2016-09-29 14:28:31

标签: ajax node.js express file-upload multer

我需要在我的请求体中访问文件名,因为我想在我的数据库中存储但我不知道处理,这是我的代码:

   var storage = multer.diskStorage({
        destination: function (req, file, callback) {
            var name = 'public/images/' + Math.floor((Math.random() * 10675712320) + 1);
            fs.mkdir(name, (err)=> {
                if (err) {
                    console.log(err);
                } else {
                    ** Im want pass name variable**  
                    callback(null, name);
                }
            });
        },
        filename: function (req, file, callback) {
            callback(null, file.originalname);
        }
    });
    var upload = multer({storage: storage}).single('userPhoto');

    app.post('/api/photo', function (req, res) {
        ***upload(req, res, function (data) {
            I need access to file name here because i want store in my db*** 
            console.log(data);

            res.end("File is uploaded");
        });
    });

我试试这种方式但不起作用:

fs.mkdir(name, (err)=> {
                    if (err) {
                        console.log(err);
                    } else {
                        callback(name, name);
                    }
                });

1 个答案:

答案 0 :(得分:1)

您可以pathreq.file.path访问var upload = multer({storage: storage}).single('userPhoto'); app.post('/api/photo', function (req, res) { upload(req, res, function (data) { console.log(req.file.path); res.end("File is uploaded"); }); });

{{1}}