I am beginner with node.js and mongodb..I try to learn file upload tutorial..It show how to upload and download the file.. So i try to also include delete function to delete the file but it is not working..Can someone please show me how to fix it? Thank you.
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;
This is my home.ejs
<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 use "body-parser": "^1.20.1", "ejs": "^3.1.8", "express": "^4.18.2", "mongoose": "^6.8.1", "multer": "^1.4.5-lts.1"
Solving delete file not functioning..I hope someone can teach me what did I do wrong.
CodePudding user response:
Add const fs = require('fs')
and change your /delete
endpoint to :
app.delete('/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');
}
});
}
});
});