当前位置: 移动技术网 > IT编程>脚本编程>NodeJs > Nodejs实现图片上传、压缩预览、定时删除功能

Nodejs实现图片上传、压缩预览、定时删除功能

2020年03月09日  | 移动技术网IT编程  | 我要评论

前言

我们程序员日常都会用到图片压缩,面对这么常用的功能,肯定要尝试实现一番。

第一步,node基本配置

这里我们用到的是koa框架,它可是继express框架之后又一个更富有表现力、更健壮的web框架。

1、引入基本配置

const koa = require('koa');// koa框架
const router = require('koa-router');// 接口必备
const cors = require('koa2-cors'); // 跨域必备
const tinify = require('tinify'); // 图片压缩
const serve = require('koa-static'); // 引入静态文件处理
const fs = require('fs'); // 文件系统
const koabody = require('koa-body'); //文件保存库
const path = require('path'); // 路径

2、使用基本配置

let app = new koa();
let router = new router();
tinify.key = ''; // 这里需要用到tinify官网的key,要用自己的哦,下面有获取key的教程。

//跨域
app.use(cors({
  origin: function (ctx) {
    return ctx.header.origin;
  },
  exposeheaders: ['www-authenticate', 'server-authorization'],
  maxage: 5,
  credentials: true,
  withcredentials: true,
  allowmethods: ['get', 'post', 'delete'],
  allowheaders: ['content-type', 'authorization', 'accept'],
}));
// 静态处理器配置
const home = serve(path.join(__dirname) + '/public/');
app.use(home);

//上传文件限制
app.use(koabody({
  multipart: true,
  formidable: {
    maxfilesize: 200 * 1024 * 1024 // 设置上传文件大小最大限制,默认2m
  }
}));

3、tinify官网的key获取方式

输入你名字跟邮箱,点击 get your api key , 就可以了。

注意: 这个api一个月只能有500次免费的机会,不过我觉得应该够了。

第二步,详细接口配置

我们要实现图片上传以及压缩,下面我们将要实现。

1、上传图片

var new1 = '';
var new2 = '';
// 上传图片
router.post('/uploadpic', async (ctx, next) => {
  const file = ctx.request.files.file; // 上传的文件在ctx.request.files.file
  // 创建可读流
  const reader = fs.createreadstream(file.path);
  // 修改文件的名称
  var mydate = new date();
  var newfilename = mydate.gettime() + '.' + file.name.split('.')[1];
  var targetpath = path.join(__dirname, './public/images/') + `${newfilename}`;
  //创建可写流
  const upstream = fs.createwritestream(targetpath);
  new1 = targetpath;
  new2 = newfilename;
  // 可读流通过管道写入可写流
  reader.pipe(upstream);
  //返回保存的路径
  console.log(newfilename)
  ctx.body ="上传成功"
});

2、压缩图片以及定时删除图片

// 压缩图片
router.get('/zipimg', async (ctx, next) => {
  console.log(new1);
   let sourse = tinify.fromfile(new1); //输入文件
   sourse.tofile(new1); //输出文件
   // 删除指定文件
   settimeout(() => {
     fs.unlinksync(new1);
   }, 20000);
   // 删除文件夹下的文件
   settimeout(() => {
     deletefolder('./public/images/')
   }, 3600000);
  let results = await change(new1);
  ctx.body = results
});
// 压缩完成替换原图
const change = function (sql) {
  return new promise((resolve) => {
       fs.watchfile(sql, (cur, prv) => {
         if (sql) {
           // console.log(`cur.mtime>>${cur.mtime.tolocalestring()}`)
           // console.log(`prv.mtime>>${prv.mtime.tolocalestring()}`)
           // 根据修改时间判断做下区分,以分辨是否更改
           if (cur.mtime != prv.mtime) {
             console.log(sql + '发生更新')
             resolve(new2)
           }
         }
       })
  })
}
// 删除指定文件夹的图片
function deletefolder(path) {
  var files = [];
  if (fs.existssync(path)) {
    if (fs.statsync(path).isdirectory()) {
      files = fs.readdirsync(path);
      files.foreach(function (file, index) {
        var curpath = path + "/" + file;
        if (fs.statsync(curpath).isdirectory()) {
          deletefolder(curpath);
        } else {
          fs.unlinksync(curpath);
        }
      });
      // fs.rmdirsync(path);
    } 
    // else {
    //   fs.unlinksync(path);
    // }
  }
}

3、端口配置

app.use(router.routes()).use(router.allowedmethods());
app.listen(6300)
console.log('服务器运行中')

第三步,前台页面配置

实现了后台的配置,那么我们将要展示实现它,页面有点low,只是为了实现基本的功能。

<!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>
  <style>
    h3{ text-align: center; }
    #progress { height: 20px; width: 500px; margin: 10px 0; border: 1px solid gold; position: relative; }
    #progress .progress-item { height: 100%; position: absolute; left: 0; top: 0; background: chartreuse; transition: width .3s linear; }
    .imgdiv{ width: 400px; text-align: center; display: none; }
    .imgdiv img{ width: 100%; }
</style>
</head>
<body>
  <h3>压缩图片</h3>
  <input type="file" id="file" accept="image/*">
  <div style="margin: 5px 0;">上传进度:</div>
  <div id="progress">
    <div class="progress-item"></div>
  </div>
  <p class="status" style="display: none;"></p>
  <div class="imgdiv">
    <img src="" alt="" class="imgbox">
  </div>
  <div class="bbt">
    <button class="btn" style="display: none;">压缩</button>
  </div>
</body>
<script>
  //上传图片
  document.queryselector("#file").addeventlistener("change", function () {
    var file = document.queryselector("#file").files[0];
    var formdata = new formdata();
    formdata.append("file", file);
    var xhr = new xmlhttprequest();
    xhr.open("post", "http://localhost:6300/uploadpic/");
    xhr.onreadystatechange = function () {
      if (xhr.readystate == 4 && xhr.status == 200) {
        document.queryselector('.btn').style.display = "block";
        document.queryselector('.status').style.display = "block";
        document.queryselector('.status').innertext=xhr.responsetext
      }
    }
    xhr.upload.onprogress = function (event) {
      if (event.lengthcomputable) {
        var percent = event.loaded / event.total * 100;
        document.queryselector("#progress .progress-item").style.width = percent + "%";
      }
    }
    xhr.send(formdata);
  });
  // 压缩图片
  document.queryselector('.btn').onclick = function () {
    document.queryselector('.status').innertext='等待中......'
    var xhr = new xmlhttprequest();
    xhr.open("get", "http://localhost:6300/zipimg/");
    xhr.send();
    xhr.onreadystatechange = function () {
      if (xhr.readystate == 4 && xhr.status == 200) {
        document.queryselector('.imgdiv').style.display = "block";
        document.queryselector('.status').innertext='压缩成功'
        document.queryselector(".imgbox").setattribute('src', './images/' + xhr.responsetext)
        document.queryselector('.btn').style.display = "none";
      }
    }
  }
</script>
</html>

总结

以上所述是小编给大家介绍的nodejs实现图片上传、压缩预览、定时删除功能,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网