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>&nbsp;&nbsp;&nbsp;&nbsp;"+getFileSize(item.size)+
                            "&nbsp;&nbsp;&nbsp;&nbsp;<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('刪除失敗')
    }
    
})

需要源碼的朋友留下郵箱!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章