简体   繁体   中英

How can I use Multer with Express.static(“public”) and EJS as view engine?

I am using multer with Express and EJS. I am saving the file path returned by multer to my database to further pass the path to the ejs template. But the file path includes the "public" folder and because I have set default view engine as ejs and express.static("public"). The path that is being stored in my database returned by multer when that is passed in the ejs template in the the image is not visible because of the file path. Is there is any way to get my images displayed properly? Here is my code:

My file structure:

  1. public>upload

    views>main.ejs

My app.js file

// Node app configs

const app = express();
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Storage Engine

const storage = multer.diskStorage({
    destination: './public/upload',
    filename: (req, file, cb) => {
        return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
    }
})

const upload = multer({
    storage: storage,
   limits:{
       fileSize: 10485760
   }
})
app.use('/profile', express.static('upload'));

//Main get method

app.get("/main", function  (req, res) {
    if (req.isAuthenticated()) {
        User.find({ "secret": { $ne: null }, "filePath": { $ne: null }}, function(err, foundUser, 
 filePath){
            if(err){
                console.log(err);
            }else{
                if(foundUser ){
                    res.render("main", {
                        usersWithSecrets: foundUser,
                        usersWithImages: filePath
                       
                    });
                    console.log(foundUser);
                }
            }
        }
        );
    } else {
        res.redirect("/login");
    }

});

Data stored in my database: 在此处输入图像描述

Remove the public/ prefix string like this:

let filePath = 'public\upload\profile_1609301637277.PNG'
filePath = filePath.split('/').slice(1).join('/')
console.log(filePath) //=> upload/profile_1609301637277.PNG

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM