如何首先制作目录,然后通过节点js中的multer上传该目录

时间:2018-04-02 20:49:52

标签: node.js multer

我想通过multer上传图片,但首先我想为每个用户创建一个目录或文件夹,然后将图片上传到该用户文件夹。

如果我自己为用户创建文件夹并上传,则传递user_id,图像会上传到该文件夹​​中。 但如果我通过代码完成,我就无法做到。

当我在目的地时,我正在添加req.body.user_id,它会给我undefined。 像这样 :-      var storage = multer.diskStorage({

        destination: function (req, file, cb) {
            cb(null, __dirname + '/images/'+ req.body.user_id)

        } 

[
app.post('/test', function (req, res) {

    var storage = multer.diskStorage({

        destination: function (req, file, cb) {
            cb(null, __dirname + '/images/' )

        },

        filename: function (req, file, cb) {
            cb(null, file.originalname + '-' + Date.now())
            //console.log(file);

        }
    });

    var upload = multer({ storage: storage }).single('image');

    var formatted = new Date().toLocaleString();



    upload(req, res, function (err) {
        var data = {
            "user_id": req.body.user_id,
            "item_id": req.body.item_id,
            "sell_type": req.body.sell_type,
            "sell_name": req.body.sell_name,
            "sell_location": req.body.sell_location,
            "sell_price": req.body.sell_price,
            "data_post": formatted
        };
              console.log("error ==>",err);
        if(err){
            res.status(400).json({
            "status_code": 'ERROR',
            "message": "image  uploadinf Fail"
            });

        }else{

            fs.exists("/var/www/html/Anoop/nodetest/images/" + data.user_id, (exists) => {
                console.log(exists);
                if(exists) {

                            res.status(200).json({
                                "status_code": "SUCCESS",
                                "message": "uploaded",
                                "data": req.file.path

                            });

                } 
                else 
                {   
                    mkdirp("/var/www/html/Anoop/nodetest/images/" + data.user_id, function (err, result) {
                        if (err) {
                            res.status(400).json({
                                "status_code": "ERROR",
                                "message": "dir not created"

                            });
                        } else {
                            //console.log(result);
                            res.status(200).json({
                                "status_code": "SUCCESS",
                                "message": "dir created",
                                "data": req.file.path

                            });

                        }
                    });

                }

            });


        }


    });

});

 ]

1 个答案:

答案 0 :(得分:1)

试试此代码

const fs = require('fs')
const filesDir = 'files';

// check if directory exists
if (!fs.existsSync(filesDir)) {
// if not create directory
    fs.mkdirSync(filesDir);

}