无法在 multer 方法中发回对象

Can't send back object in multer method

我正在通过 multer 执行文件上传,因为我想将文件存储在特定位置,并为其命名我自己的文件名,所以我使用 destinationfilename multer 在创建存储对象时提供的属性。

我遇到的问题是我想在将新创建的对象存储到数据库中后将其信息发送回客户端。但是,没有 res 参数可以执行此操作,我只能在我的 post 方法中执行此操作,该方法没有我刚刚创建的对象。

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads'); // Absolute path. Folder must exist, will not be created for you.
    },
    filename: function (req, file, cb) {
        var fileType = file.mimetype.split("/")[1];
        var fileDestination = file.originalname + '-' + Date.now() + "." + fileType;

        cb(null, fileDestination);

        var map = new Map({
            mapName: req.body.mapTitle,
            mapImagePath: "./uploads/" + fileDestination,
            ownerId: req.user._id
        });

        Map.createMap(map, function(err, map){
            if(err)
                next(err);
            console.log(map);
        });
    }
});

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

router.post('/', upload.single('mapImage'), function (req, res) {

    res.status(200).send({
        code: 200, success: "Map Created."
    });

});

Multer 将文件附加到请求对象,您可以在 post 方法中访问这些文件:

app.post('/', upload.single('mapImage'), function (req, res, next) {
    console.log(req.file.filename); // prints the filename
    console.log(req.file.destination); // prints the directory
    console.log(req.file.path); // prints the full path (directory + filename)
    console.log(req.file.originalname); // prints the name before you renamed it
    console.log(req.file.size); // prints the size of the file (in bytes)

    res.json(req.file);
});