Home > Back-end >  How to show file name in upload file nodejs
How to show file name in upload file nodejs

Time:01-17

I am beginner that try to learn file upload using nodejs an mongodb. When I watch the tutorial and follow it the file upload would be in image form..But if I try to upload file it will show blank image box..I try to change the format into showing it like file name..For example is if upload pdf it will just show beginning_tutorial.pdf so that we can know what file we upload..I using multer but I dont know how to change it to show file name intead of image..Can someone show me..I really appreciate it, if you can help me understand how to make that..Thank you a lot.

This is my app.js
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const mongoose = require('mongoose');
const path = require('path');
const fs = require('fs')

const app = express();

const storage = multer.diskStorage({
    destination:function(req,file,cb){
         cb(null,'./public/uploads')
    },
    filename(req,file,cb){
        cb(null,file.originalname)
    }
})

const upload = multer({storage:storage});

 mongoose.connect('mongodb://localhost:27017/files',{useNewUrlParser:false})
 .then(()=>console.log('connect')).catch(err=>console.log(err))


const fileSchema = new mongoose.Schema({
    filespath:String
})


 const fileModel = mongoose.model('filesdemo',fileSchema)


app.set('view engine','ejs');

app.set("views",path.resolve(__dirname,'views'));

const filePath = path.resolve(__dirname,'public');

app.use(express.static(filePath));

app.use(bodyParser.urlencoded({extended:false}))

app.get('/',(req,res)=>{
    fileModel.find((err,data)=>{
             if(err){
                 console.log(err)
             }
            if(data){
                console.log(data)
                res.render('home',{data:data})
            } 
           else{
               res.render('home',{data:{}})
           } 
    })
    
})

app.post('/',upload.single('file'),(req,res)=>{
    const x= 'uploads/' req.file.originalname;
    const files = new fileModel({
        filespath:x
    })
    files.save((err,data)=>{
         if(err){
             console.log(err)
         }
         else{
             console.log('data',data)
            res.redirect('/')
         }
    })
})

app.get('/download/:id',(req,res)=>{
     fileModel.find({_id:req.params.id},(err,data)=>{
         if(err){
             console.log(err)
         } 
         else{
            const path= __dirname '/public/' data[0].filespath;
            res.download(path);
         }
     })
})

app.get('/delete/:id', (req, res) => {
    fileModel.find({_id: req.params.id}, (err, data) => {
        if(err) {
            console.log(err);
            res.send(err);
        } else {
            const path= __dirname '/public/' data[0].filespath;
            fs.unlink(path, (err) => {
                if (err) throw err;
                console.log(path   ' was deleted');
            });

            fileModel.deleteOne({ _id: req.params.id }, (err) => {
                if (err) {
                    console.log(err);
                    res.send(err);
                } else {
                    console.log('File deleted successfully');
                    res.send('File deleted successfully');
                }
            });
        }
    });
});

const port = process.env.PORT || 3000 ;
app.listen(port,()=>console.log(`server running at ${port}`))

module.exports = app;

and this is my home.ejs for view

<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>
     
     <center>
        <h2>Upload Files</h2>
        <form action="/" method="POST" enctype="multipart/form-data">
         <input type="file" name="file"><br>
         <input type="submit" value="Upload">
        </form><br><br><br><br>
    </center>
    <h2>Download Files</h2>
        <table>
            <thead>
                <tr>
                    <td>
                        image
                    </td>
                    <td>
                        download
                    </td>
                </tr>
            </thead>
            <tbody>
                <% for(var i=0; i < data.length > 0; i  ) {%>
                 <tr>
                     <td><img src="<%= data[i].filespath %>" style="width:100px; height:100px;"></td>
                     <td>
                         <form action="/download/<%= data[i]._id %>" method="GET">
                          <input type="submit" value="Download">
                        </form>
                        <form action="/delete/<%= data[i]._id %>" method="GET">
                            <input type="submit" value="Delete">
                          </form>
                     </td>
                 </tr>
                <% } %>

            
            </tbody>
        </table>
 </body>
 </html>

I'm using this package. The file upload I put it under public/uploads

"body-parser": "^1.20.1",
    "ejs": "^3.1.8",
    "express": "^4.18.2",
    "fs": "^0.0.1-security",
    "mongoose": "^6.8.1",
    "multer": "^1.4.5-lts.1"

CodePudding user response:

you need to change you ejs file, ejs file is a html model, map your page.as your desire, you want to show filename replace image,so:

<td><img src="<%= data[i].filespath %>" style="width:100px; height:100px;"></td>

this line change to:

<td><%= data[i].filespath %></td>

maybe work!

  • Related