0

I am using express-fileupload to upload the images. The images are saved in my local directory. I want to insert the name of the file to the mongodb if possible. Finally I want the image to be displayed in my frontend.

    function insertRecord(req,res){
    if(req.files){
    const file=req.files.filename
    filename=file.name
    file.mv("./upload"+filename,function(err){
        if(err)
        console.log(err)
    })
}
    const user=new User()
    user.name=req.body.name
    user.address=req.body.address
    user.email=req.body.email
    user.mobile=req.body.mobile
    user.filename=req.body.filename
    user.save((err,docs)=>{
        if(!err){
        res.redirect('/user/list')
        }
        else {
            if (err.name == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("./users/addOrEdit", {
                    viewTitle: "Insert User",
                    user: req.body
                });
            }
            else
                console.log('Error during record insertion : ' + err);
        }
    });
}

I am not sure whether the way to insert the name of the file to the mongodb is correct or not. Anyway, that is optional but I am not understanding how can I display the uploaded images which are present in the local directory. I tried to save the image as base64 but the record is not saved to the database now.

    var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads/')
    },
    filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now())
    }
  })

  var upload = multer({ storage: storage })

router.post('/',upload.single('myImage'),function(req,res){
    if (req.body._id == '')
        insertRecord(req, res);

        else
        updateRecord(req, res);
})


function insertRecord(req,res){
var img = fs.readFileSync(req.file.path);
var encode_image = img.toString('base64');  
 var finalImg = {
      contentType: req.file.mimetype,
      image:  new Buffer(encode_image, 'base64')
   };

    const user=new User()
    user.name=req.body.name
    user.address=req.body.address
    user.email=req.body.email
    user.mobile=req.body.mobile
    user.save(finalImg,(err,docs)=>{
        if(!err){
        res.redirect('/user/list')
        }
        else {
            if (err.name == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("./users/addOrEdit", {
                    viewTitle: "Insert User",
                    user: req.body
                });
            }
            else
                console.log('Error during record insertion : ' + err);
        }
    });
}
  • https://www.tutorialsteacher.com/nodejs/serving-static-files-in-nodejs this might help you understand how you can show images – mdln97 Apr 06 '20 at 10:14

1 Answers1

0

Edit: I think there is a problem in the code: it should be `'./upload/'+filename' not without the second slash.

In order to show the images, you have to open a static route in Express. Example: app.use('/images', express.static(PATH)). Then you can, in the frontend, call it as <img src="URL/images/FILENAME" />

From your code, it is not possible to understand what kind of data you are sending to the server. As far as I understand, you're trying mv the string filename. In order to transfer files (such as images), you should have form-data instead of JSON data or you should encode the image file into Base64 to transfer it as text (not the filename, the whole file).

Check Multer out for this kind of job. It is described well in the README.md. Apart from that, until you submit the form, the image won't be available in the front-end. If you want to preview the image before uploading it's a separate process which you can learn more in here.

Yanek Yuk
  • 74
  • 2
  • 10