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

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

第一步,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>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.duanlonglong.com/qdjy/1109.html