Search code examples
node.jsmongooseejsmulterbody-parser

Uploading image in Nodejs


I tried to follow some tutorials for upload file in node js..but it seem the upload for image is not working. It show

Error: ENOENT: no such file or directory, open 'C:\Users\User\Downloads\fileuplloaddownload-master\public\uploads\pexels-luiisrtz-1693399.jpg'

I try to find the mistake in the code but it seem that I do it correctly. Can it be the code is outdated?

This is my code for app.js

    var express = require('express');
    var mongoose = require('mongoose');
    var bodyParser = require('body-parser');
    var multer =  require('multer');
    var path = require('path');
    
    var picSchema= new mongoose.Schema({
        picpath:String
    })
    
    var picModel = mongoose.model('picsdemo',picSchema);
    
    var storage = multer.diskStorage({
        destination:function(req,file,cb){
            cb(null,'./public/uploads')
        },
        filename:function(req,file,cb){
            cb(null,file.originalname)
        }
    })
    var upload = multer({storage:storage})
    
    var app = express();
    
    mongoose.connect('mongodb://localhost:27017/pics',{useNewUrlParser:true})
    .then(()=>console.log('connected')).catch(err=>console.log('error ocured',err));
    
    app.set('views',path.resolve(__dirname,'views'));
    app.set('view engine','ejs');
    
    var pathh = path.resolve(__dirname,'public');
    app.use(express.static(pathh));
    app.use(bodyParser.urlencoded({extended:false}));
    
    
    app.get('/',(req,res)=>{
        picModel.find((err,data)=>{
            if(err){
                console.log(err)
            }
            else if(data.length>0){
                res.render('home',{data:data})
            }
            else{
                res.render('home',{data:{}})
            }
        })
    })
    
    app.post('/',upload.single('pic'),(req,res)=>{
        var x = 'uploads/'+req.file.originalname;
        var temp = new picModel({
            picpath:x
        })
        temp.save((err,data)=>{
            if(err){
                console.log(err)
            }
            res.redirect('/')
        })
    })
    
    app.get('/download/:id',(req,res)=>{
        picModel.find({_id:req.params.id},(err,data)=>{
             if(err){
                 console.log(err)
             }
             else{
                 var x= __dirname+'/public/'+data[0].picpath;
                 res.download(x)
             }
        })
    })
    
    var port  = process.env.PORT || 3000 ;
    app.listen(port,()=>console.log('server running at port'+port))

This home.ejs code for the website layout

 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     <title>Document</title>
 </head>
 <body>
      <form action="/" method="POST" enctype="multipart/form-data">
      <input type="file" name="pic" id="pic"><br>
      <input type="submit" value="upload file">
    </form><br><br><br><br>
    <% if(data.length > 0) {%>
      <table>
           <thead>
               <tr>
                   <td>
                       images
                   </td>
                   <td>
                       download
                   </td>
               </tr>
           </thead>
           <tbody>
               <% for(var i=0; i< data.length; i++) {%>
               <tr>
                   <td>
                 <img src="<%= data[i].picpath%>" alt="images" style="width:100px; height:100px;">
                   </td>
                   <td>
                <form action="/download/<%= data[i]._id%>">
                 <input type="submit" value="download">
                </form>
                   </td>
               </tr>
               <% } %>
           </tbody>
      </table>
      <% } %>  
 </body>
 </html>

In this code I use this dependancies

"body-parser": "^1.19.0", "ejs": "^2.7.1", "express": "^4.17.1", "mongoose": "^5.7.7", "multer": "^1.4.2"


Solution

  • Multer will try to put uploaded images to public/uploads folder, but that folder probably does not exist.

    Try creating public folder and uploads folder inside of it, and then try again.