MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

comment télécharger l'image dans un dossier à l'aide de nodejs et enregistrer le chemin dans mongodb ?

Vous pouvez utiliser nodejs formidable et le module fs-extra pour créer un dossier pour stocker l'image dans votre application.Essayez ceci

var fs = require('fs-extra');
var formidable = require('formidable');
var EmpDetail   = require('../models/employee.model.js');//This line means that I am having my schema code.
var    util = require('util');


app.route('/upload').post(function(req,res){

res.json({success:true});

var empData = new EmpDetail();//Here I created object to call my schema values.

var form   =  new formidable.IncomingForm();
console.log(req.body,'req.body');
form.parse(req,function(err,fields,files){
    console.log('dfgbfbf');
    util.inspect({fields: fields, files: files});
});

form.on('field',function(name,value){//This means your html input fields
    console.log('fields',name,value);
    if(name == 'fullName'){
        console.log('here',value);
        empData.fullName = value;
    }
    if(name == 'fatherName'){
        empData.fatherName = value;
    }
    if(name == 'dt'){
        empData.DOB = value;
    }
});
form.on('file',function(field, file){//This means on click of file it gets that file.
    console.log(file.name,'hjgjg');
    var temp = file.path;
    console.log(temp,'temp',file.name);
    var fileName = file.name;
        var fileName = file.name;
        var location     = 'images/';
        var cpLocation   = 'empDetails/images/';
        empData.imgSize = file.size;
        empData.imgType = file.type;
        empData.picFile = location+fileName;//Here PicFile is name of Avatar in model
fs.copy(temp,cpLocation+fileName ,function(err){//This means it create a folder and name of the image in your app.
        if(err)
        {
            console.log(err);
        }
    });

});
form.on('end',function(fields, files){

        empData.save(function(err,resobj){
            if(err)
            {    
               throw err;
            }
        });
});
});