自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Nodejs實現(xiàn)圖片的上傳、壓縮預(yù)覽、定時刪除

開發(fā) 前端
日常都會用到圖片壓縮,面對這么常用的功能,今天就簡單介紹一下Nodejs實現(xiàn)圖片的上傳、壓縮預(yù)覽、定時刪除。

前言

我們程序員日常都會用到圖片壓縮,面對這么常用的功能,肯定要嘗試實現(xiàn)一番。 

第一步,node基本配置

這里我們用到的是koa框架,它可是繼express框架之后又一個更富有表現(xiàn)力、更健壯的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'); // 引入靜態(tài)文件處理 
  6. const fs = require('fs'); // 文件系統(tǒng) 
  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官網(wǎng)的KEY,要用自己的哦,下面有獲取key的教程。 
  4.  
  5. //跨域 
  6. app.use(cors({ 
  7.     origin: function (ctx) { 
  8.         return ctx.header.origin; 
  9.     }, 
  10.     exposeHeaders: ['WWW-Authenticate''Server-Authorization'], 
  11.     maxAge: 5, 
  12.     credentials: true
  13.     withCredentials: true
  14.     allowMethods: ['GET''POST''DELETE'], 
  15.     allowHeaders: ['Content-Type''Authorization''Accept'], 
  16. })); 
  17. // 靜態(tài)處理器配置 
  18. const home = serve(path.join(__dirname) + '/public/'); 
  19. app.use(home); 
  20.  
  21. //上傳文件限制 
  22. app.use(koaBody({ 
  23.     multipart: true
  24.     formidable: { 
  25.         maxFileSize: 200 * 1024 * 1024 // 設(shè)置上傳文件大小最大限制,默認(rèn)2M 
  26.     } 
  27. })); 

3、tinify官網(wǎng)的key獲取方式 

https://tinypng.com/developers

輸入你名字跟郵箱,點擊 Get your API key , 就可以了。

注意:這個API一個月只能有500次免費的機會,不過我覺得應(yīng)該夠了。 

第二步,詳細(xì)接口配置

我們要實現(xiàn)圖片上傳以及壓縮,下面我們將要實現(xiàn)。 

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.     // 創(chuàng)建可讀流 
  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.     //創(chuàng)建可寫流 
  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.                      // 根據(jù)修改時間判斷做下區(qū)分,以分辨是否更改 
  26.                      if (cur.mtime != prv.mtime) { 
  27.                          console.log(sql + '發(fā)生更新'
  28.                          resolve(new2) 
  29.                      } 
  30.                  } 
  31.              }) 
  32.     }) 
  33. // 刪除指定文件夾的圖片 
  34. function deleteFolder(path) { 
  35.     var files = []; 
  36.     if (fs.existsSync(path)) { 
  37.         if (fs.statSync(path).isDirectory()) { 
  38.             files = fs.readdirSync(path); 
  39.             files.forEach(function (file, index) { 
  40.                 var curPath = path + "/" + file; 
  41.                 if (fs.statSync(curPath).isDirectory()) { 
  42.                     deleteFolder(curPath); 
  43.                 } else { 
  44.                     fs.unlinkSync(curPath); 
  45.                 } 
  46.             }); 
  47.             // fs.rmdirSync(path); 
  48.         }  
  49.         // else { 
  50.         //     fs.unlinkSync(path); 
  51.         // } 
  52.     } 

3、端口配置

  1. app.use(router.routes()).use(router.allowedMethods()); 
  2. app.listen(6300) 
  3. console.log('服務(wù)器運行中'

第三步,前臺頁面配置

實現(xiàn)了后臺的配置,那么我們將要展示實現(xiàn)它,頁面有點low,只是為了實現(xiàn)基本的功能。

  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: absoluteleft: 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.  
  71. </html> 

 

 

責(zé)任編輯:姜華 來源: 前端歷劫之路
相關(guān)推薦

2022-07-17 11:22:35

前端開發(fā)圖片裁切壓縮上傳

2020-05-07 09:45:16

前端JS圖片壓縮

2017-07-04 15:10:20

移動端圖片旋轉(zhuǎn)壓縮

2009-11-24 14:45:08

PHP批量上傳圖片

2024-04-19 08:31:40

Android屬性讀取

2024-07-04 08:26:12

AndroidJPEG圖片

2021-08-27 08:38:10

CSS 技巧 resize

2017-11-21 14:14:04

PHPnode.js圖片訪問

2022-01-18 08:12:02

Markdown編輯器拍云

2021-03-04 08:33:20

JavaScript 前端原生js

2009-11-24 16:09:44

PHP Ajax

2009-12-17 14:36:57

Ruby on Rai

2016-11-09 10:28:36

Nodejs文件上傳express+mul

2009-07-07 15:07:59

JSP上傳圖片

2012-05-08 09:38:03

jQuery

2011-07-25 16:41:16

Sencha Touc

2018-10-29 09:24:41

Web圖片壓縮網(wǎng)頁加速

2023-01-15 20:28:32

前端圖片壓縮

2023-11-04 12:43:44

前端圖片參數(shù)

2022-08-08 08:29:55

圖片壓縮前端互聯(lián)網(wǎng)
點贊
收藏

51CTO技術(shù)棧公眾號