nodejs+express4实现文件上传下载删除和列表展示功能
0.效果展示
1.创建项目
创建文件夹:express_file_upload
npm init
# 入口文件选择server.js
- 安装插件
npm install express
npm install nodemon -g
npm install body-parser multer
npm install ejs
2.上传文件
-
上传页面
<!DOCTYPE html> <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>文件上传</title> </head> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="提交"> </form> <body> </body> </html>
-
路由
// 上传页面 router.get('/', (req, res)=>{ console.log(__dirname) res.sendFile(path.join(__dirname,'../views/upload.html')) }) // 上传文件 router.post('/upload', upload.single('file'), function(req, res) { console.dir(req.files) if (!req.file || Object.keys(req.file).length === 0) { res.status(400).send('请选择要上传的文件!'); return; } // res.send('Success.'); // 重定向到列表页 res.redirect('/filelist') });
3.文件列表
-
列表展示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>文件列表</title> </head> <body> <h4>文件列表</h4> <ul id="filelist"></ul> <script src="/static/jquery.js"></script> <script> $(function(){ init(); }) function init(){ $.ajax({ type: 'GET', url:'/getFileList', success: function(data){ console.log(data) $.each(data, function(index,item){ $("#filelist").append("<li><a href='/download?path="+item.path+"'>"+ item.name+"</a> "+getFileSize(item.size)+ " <button οnclick='deleteFile(\""+item.path+"\")'>删除</button></li>"); }) } }) } function getFileSize(size){ if(size < 1024){ return size+'KB' }else if(size >= 1024&&size<Math.pow(1024, 3)){ return (size/1024.0/1024).toFixed(2)+'MB' }else{ return (size/1024.0/1024/1024).toFixed(2)+'GB' } } function deleteFile(path){ var param={"path": path}; console.log(path) if (confirm('确定删除?')){ $.ajax({ type: 'POST', url:'/delete?path='+path, data: JSON.stringify(param), success: function(data){ window.location.reload(); } }) } return false; } </script> </body> </html>
-
路由
// 列表页面 router.get('/filelist',function(req, res){ res.sendFile(path.join(__dirname,'../views/filelist.html')) }) // 获取文件列表 router.get('/getFileList',function(req, res, next){ var filelist = getFileList('upload') res.send(filelist) }) function getFileList(path){ var filelist = []; readFile(path, filelist); return filelist; } function readFile(path, filelist){ var files = fs.readdirSync(path); files.forEach(walk); function walk(file) { var state = fs.statSync(path+'/'+file) if(state.isDirectory()){ readFile(path+'/'+file, filelist) }else{ var obj = new Object; obj.size = state.size; obj.name = file; obj.path = path+'/'+file; filelist.push(obj); } } }
4.下载文件
// 下载文件
router.get('/download',function(req,res){
var filePath = req.query.path;
console.log('下载文件:'+filePath)
filePath = path.join(__dirname,'../'+filePath);
res.attachment(filePath)
res.sendFile(filePath)
})
5.删除文件
// 删除文件
router.post('/delete', function(req, res, next){
var filePath = req.query.path;
console.log('删除文件:'+filePath)
try {
fs.unlinkSync(filePath)
// 重定向到列表页
res.send('删除成功')
} catch (error) {
res.send('删除失败')
}
})
源码地址
https://gitee.com/indexman/express_file_upload
路过的给老徐点个赞加个关注收藏:)
分类:
Web前端
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构