欢迎访问成都祈钰瑶科技有限公司!

全国免费服务热线:

18982081108
✕

成都网站设计公司,成都响应式网站设计,成都移动端网站设计,成都网站UI设计

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

前言

创新互联公司坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都网站设计、成都网站制作、外贸网站建设、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的抚宁网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

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

第一步,node基本配置

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

1、引入基本配置

 
 
 
 
  1. const Koa = require('koa');// koa框架
  2. const Router = require('koa-router');// 接口必备
  3. const cors = require('koa2-cors'); // 跨域必备
  4. const tinify = require('tinify'); // 图片压缩
  5. const serve = require('koa-static'); // 引入静态文件处理
  6. const fs = require('fs'); // 文件系统
  7. const koaBody = require('koa-body'); //文件保存库
  8. const path = require('path'); // 路径

2、使用基本配置

 
 
 
 
  1. let app = new Koa();
  2. let router = new Router();
  3. tinify.key = ''; // 这里需要用到tinify官网的KEY,要用自己的哦,下面有获取key的教程。
  4. //跨域
  5. app.use(cors({
  6.     origin: function (ctx) {
  7.         return ctx.header.origin;
  8.     },
  9.     exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  10.     maxAge: 5,
  11.     credentials: true,
  12.     withCredentials: true,
  13.     allowMethods: ['GET', 'POST', 'DELETE'],
  14.     allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
  15. }));
  16. // 静态处理器配置
  17. const home = serve(path.join(__dirname) + '/public/');
  18. app.use(home);
  19. //上传文件限制
  20. app.use(koaBody({
  21.     multipart: true,
  22.     formidable: {
  23.         maxFileSize: 200 * 1024 * 1024 // 设置上传文件大小最大限制,默认2M
  24.     }
  25. }));

3、tinify官网的key获取方式

https://tinypng.com/developers

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

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

第二步,详细接口配置

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

1、上传图片

 
 
 
 
  1. var new1 = '';
  2. var new2 = '';
  3. // 上传图片
  4. router.post('/uploadPic', async (ctx, next) => {
  5.     const file = ctx.request.files.file; // 上传的文件在ctx.request.files.file
  6.     // 创建可读流
  7.     const reader = fs.createReadStream(file.path);
  8.     // 修改文件的名称
  9.     var myDate = new Date();
  10.     var newFilename = myDate.getTime() + '.' + file.name.split('.')[1];
  11.     var targetPath = path.join(__dirname, './public/images/') + `${newFilename}`;
  12.     //创建可写流
  13.     const upStream = fs.createWriteStream(targetPath);
  14.     new1 = targetPath;
  15.     new2 = newFilename;
  16.     // 可读流通过管道写入可写流
  17.     reader.pipe(upStream);
  18.     //返回保存的路径
  19.     console.log(newFilename)
  20.     ctx.body ="上传成功"
  21. });

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

 
 
 
 
  1. // 压缩图片
  2. router.get('/zipimg', async (ctx, next) => {
  3.     console.log(new1);
  4.      let sourse = tinify.fromFile(new1); //输入文件
  5.      sourse.toFile(new1); //输出文件
  6.      // 删除指定文件
  7.      setTimeout(() => {
  8.          fs.unlinkSync(new1);
  9.      }, 20000);
  10.      // 删除文件夹下的文件
  11.       setTimeout(() => {
  12.           deleteFolder('./public/images/')
  13.       }, 3600000);
  14.       
  15.     let results = await change(new1);
  16.     ctx.body = results
  17. });
  18. // 压缩完成替换原图
  19. const change = function (sql) {
  20.     return new Promise((resolve) => {
  21.              fs.watchFile(sql, (cur, prv) => {
  22.                  if (sql) {
  23.                      // console.log(`cur.mtime>>${cur.mtime.toLocaleString()}`)
  24.                      // console.log(`prv.mtime>>${prv.mtime.toLocaleString()}`)
  25.                      // 根据修改时间判断做下区分,以分辨是否更改
  26.                      if (cur.mtime != prv.mtime) {
  27.                          console.log(sql + '发生更新')
  28.                          resolve(new2)
  29.                      }
  30.                  }
  31.              })
  32.     })
  33. }
  34. // 删除指定文件夹的图片
  35. function deleteFolder(path) {
  36.     var files = [];
  37.     if (fs.existsSync(path)) {
  38.         if (fs.statSync(path).isDirectory()) {
  39.             files = fs.readdirSync(path);
  40.             files.forEach(function (file, index) {
  41.                 var curPath = path + "/" + file;
  42.                 if (fs.statSync(curPath).isDirectory()) {
  43.                     deleteFolder(curPath);
  44.                 } else {
  45.                     fs.unlinkSync(curPath);
  46.                 }
  47.             });
  48.             // fs.rmdirSync(path);
  49.         } 
  50.         // else {
  51.         //     fs.unlinkSync(path);
  52.         // }
  53.     }
  54. }

3、端口配置

 
 
 
 
  1. app.use(router.routes()).use(router.allowedMethods());
  2. app.listen(6300)
  3. console.log('服务器运行中')

第三步,前台页面配置

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

 
 
 
 
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7.     <title>压缩图片</title>
  8.     <style>
  9.         h3{ text-align: center; }
  10.         #progress { height: 20px; width: 500px; margin: 10px 0; border: 1px solid gold; position: relative; }
  11.         #progress .progress-item { height: 100%; position: absolute; left: 0; top: 0; background: chartreuse;  transition: width .3s linear; }
  12.         .imgdiv{ width: 400px; text-align: center; display: none; }
  13.         .imgdiv img{ width: 100%; }
  14. </style>
  15. </head>
  16. <body>
  17.     <h3>压缩图片</h3>
  18.     <input type="file" id="file" accept="image/*">
  19.     <div style="margin: 5px 0;">上传进度:</div>
  20.     <div id="progress">
  21.         <div class="progress-item"></div>
  22.     </div>
  23.     <p class="status" style="display: none;"></p>
  24.     <div class="imgdiv">
  25.         <img src="" alt="" class="imgbox">
  26.     </div>
  27.     <div class="bbt">
  28.         <button class="btn" style="display: none;">压缩</button>
  29.     </div>
  30. </body>
  31. <script>
  32.     //上传图片
  33.     document.querySelector("#file").addEventListener("change", function () {
  34.         var file = document.querySelector("#file").files[0];
  35.         var formdata = new FormData();
  36.         formdata.append("file", file);
  37.         var xhr = new XMLHttpRequest();
  38.         xhr.open("post", "http://localhost:6300/uploadPic/");
  39.         xhr.onreadystatechange = function () {
  40.             if (xhr.readyState == 4 && xhr.status == 200) {
  41.                 document.querySelector('.btn').style.display = "block";
  42.                 document.querySelector('.status').style.display = "block";
  43.                 document.querySelector('.status').innerText=xhr.responseText
  44.             }
  45.         }
  46.         xhr.upload.onprogress = function (event) {
  47.             if (event.lengthComputable) {
  48.                 var percent = event.loaded / event.total * 100;
  49.                 document.querySelector("#progress .progress-item").style.width = percent + "%";
  50.             }
  51.         }
  52.         xhr.send(formdata);
  53.     });
  54.     // 压缩图片
  55.     document.querySelector('.btn').onclick = function () {
  56.         document.querySelector('.status').innerText='等待中......'
  57.         var xhr = new XMLHttpRequest();
  58.         xhr.open("get", "http://localhost:6300/zipimg/");
  59.         xhr.send();
  60.         xhr.onreadystatechange = function () {
  61.             if (xhr.readyState == 4 && xhr.status == 200) {
  62.                 document.querySelector('.imgdiv').style.display = "block";
  63.                 document.querySelector('.status').innerText='压缩成功'
  64.                 document.querySelector(".imgbox").setAttribute('src', './images/' + xhr.responseText)
  65.                 document.querySelector('.btn').style.display = "none";
  66.             }
  67.         }
  68.     }
  69. </script>
  70. </html>