基于koa2实现文件上传

1. routes-authors.js

const router = require('koa-router')(),
      fs = require('fs'),
      authors = require('../models/authors');

router.post('/upload',async (ctx,next) => {
  const files = ctx.request.files.file;
  console.log(files.length);
  if(!files.length == true){
    let path = files.filepath;
    let name = files.originalFilename;
    let type = files.mimetype;
    if(type == 'image/jpeg' || 'image/png' || 'image/jpg')
    await authors.upImage(path,name);
    ctx.body = "上传成功";
  }else{
    for(let file of files){
    let path = file.filepath;
    let name = file.originalFilename;
    let type = file.mimetype;
    //上传文件类型过滤
    if(type == 'image/jpeg' || 'image/png' || 'image/jpg')
    //上传文件
    await authors.upImage(path,name);
    ctx.body = "上传成功";
  }}
});

router.get('/delete',async(ctx,next)=>{
  const id = ctx.request.query.id;
  await authors.deleteImage(id);
  ctx.body = '响应成功'
})
//用于获取文件信息
router.get('/show',async (ctx,next) => {
  let arr = [];
  let page = 0;
  let limit = 10;
  let a = await authors.showImage(page);
  let data = a.data;
  data.forEach(item=>{
    const file_data = fs.readFileSync(`${item.url}`);
    const buffer = new Buffer.from(file_data,'binary');
    let data1 = buffer.toString('base64');
    arr.push({'id':item.id,'base':data1,'filename':item.filename});
  });
  ctx.body = arr;
})

router.get('/page',async (ctx,next)=> {
  let arr = [];
  const page = ctx.request.query.page;
  let limit = 10;
  let a = await authors.showImage(page);
  let data = a.data;
  console.log(data.length);
  data.forEach(item=>{
    const file_data = fs.readFileSync(`${item.url}`);
    const buffer = new Buffer.from(file_data,'binary');
    let data1 = buffer.toString('base64');
    arr.push({'id':item.id,'base':data1,'filename':item.filename
  })
  });
  ctx.body = arr;  
})

//用于获取数据库中数据条数
router.get('/num',async (ctx,next) => {
  let num = await authors.count();
  ctx.body = num;
})

module.exports = router;

2. models-authors.js

const {con,ResData} = require('./mysql.js');

async function upImage(url,name){
    const res = new ResData();
    const insert = `INSERT INTO img (url,filename) VALUES("${url}","${name}")`;
    let [rows] = await con.execute(insert);
    res.data = rows;
    return res;
}
async function showImage(page){
  const res = new ResData();
  const sql = `select * from img order by id limit ${(page)*10},10;`;
  //const sql = 'select * from img order by id;';
  let [rows] = await con.execute(sql);
  res.data = rows;
  return res;
}

async function deleteImage(id){
  const res = new ResData();
  const sql = `delete from img where id='${id}';`
  let [rows] = await con.execute(sql);
  res.data = rows;
  return res;
}

async function count(){
  const res = new ResData();
  const sql = 'select count(*) count from img;' ;
  let [rows] = await con.execute(sql);
  res.data = rows;
  return res;
}

module.exports = {
    upImage,
    showImage,
    deleteImage,
    count
};

3. models-mysql.js

const mysql = require('mysql2/promise');

class ResData{
  constructor(){
    this.code = 0,
    this.msg = 'ok',
    this.count = 0,
    this.data = '';
  }
}

let con = '';
(async ()=>{
  con = mysql.createPool({
    host:'localhost',
    user:'root',
    password:'ddd',
    database:'imageUpload'
  });
})();

module.exports = {
  con,
  ResData
}

4. 前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <style>
        img{
            width:200px;
            height: 200px;
            padding: 10px 10px 10px 10px;
        }
        li{
            float: left;
            list-style: none;
            border: 1px solid red;
        }
        #img{
            margin-top: 30px;
        }
        #pageBtn{
            position:absolute;
            margin-top: -20px;
        }
        #pageBtn button{
            width: 30px;
            float: left;
        }   
    </style>
</head>
<body>
    <form 
    action="http://192.168.128.166:3000/upload" 
    method="post"
    target="nm_iframe"
    enctype="multipart/form-data">
        <input type="file" name="file" id="file" value="" multiple="multiple" />
        <input type="submit"value="提交"/>
    </form>
    <button onclick="show()"> 显示图片 </button>
    <iframe id="id_iframe" name="nm_iframe" style="display:none;"></iframe> 
    <div id="img">
    </div>
    <div id="pageBtn">
    </div>
    <script>
        let arr = [];
        let node = '';

        function show(){
            document.getElementById('img').innerHTML='';
            document.getElementById('pageBtn').innerHTML='';
            fetch('http://192.168.128.166:3000/show')
            .then(res=>{
                console.log(res.text()
                .then((result)=>{
                    let a = JSON.parse(result);
                    for(var key in a){ 
                        var li = document.createElement('li');
                        li.innerHTML = "<div id="
                                        + a[key].id +"><img src='"+ "data:image/png;base64,"
                                        +a[key].base +"' /> <p>"+a[key].filename +"</p>"
                                        +"<button onClick=deleteImg("+ a[key].id +")>删除</button></div>" 
                        document.getElementById('img').appendChild(li);
                    }
                }))
            });
            fetch('http://192.168.128.166:3000/num')
            .then(res=>{
                console.log(res.text()
                    .then((result)=>{
                        let num = JSON.parse(result);
                        let count = num.data[0].count-1;
                        let page = parseInt(count/10)+1;
                        if(count == 10){
                            page = 1
                        }
                        document.getElementById('pageBtn').innerHTML='';
                        if(count+1!=0){
                        for(let i=0;i<page;i++){
                            var btn = document.createElement('button');
                            btn.id = i;
                            btn.innerHTML = i+1;
                            btn.addEventListener('click',function(){
                                $.ajax({
                                    method:'get',
                                    url:"http://192.168.128.166:3000/page?",
                                    params:i,
                                    data:{'page':i}
                                })
                                fetch('http://192.168.128.166:3000/page?page='+i)
                                    .then(res=>{
                                        document.getElementById('img').innerHTML="";
                                        console.log(res.text()
                                        .then((result)=>{
                                            let a = JSON.parse(result);
                                            for(var key in a){ 
                                                var li = document.createElement('li');
                                                li.innerHTML = "<div id="
                                                                + a[key].id +"><img src='"+ "data:image/png;base64,"
                                                                +a[key].base +"' /> <p>"+a[key].filename +"</p>"
                                                                +"<button onClick=deleteImg("+ a[key].id +")>删除</button></div>" 
                                                document.getElementById('img').appendChild(li);
                                            }
                                        }))
                                    });
                                })
                            document.getElementById('pageBtn').appendChild(btn);
                        }}
                    })
                )
            })
        }


        function deleteImg(id){
            fetch('http://192.168.128.166:3000/num')
            .then(res=>{
                console.log(res.text()
                    .then((result)=>{
                        show();
                        let num = JSON.parse(result);
                        let count = num.data[0].count-1;
                        console.log(count);
                        let page = parseInt(count/10)+1;
                        if(count == 10){
                            page = 1
                        }
                        console.log(page);
                        document.getElementById('pageBtn').innerHTML='';
                        for(let i=0;i<page;i++){
                            var btn = document.createElement('button');
                            btn.id = i;
                            btn.innerHTML = i+1;
                            document.getElementById('pageBtn').appendChild(btn);
                        }
                    })
                )
            })
            document.getElementById(id).remove();
            $.ajax({
                method:'get',
                url:"http://192.168.128.166:3000/delete?",
                params:id,
                data:{'id':id}
            })
        }
    </script>
</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值