Nodejs實(shí)現(xiàn)圖片上傳、壓縮預(yù)覽、定時(shí)刪除功能
前言
我們程序員日常都會(huì)用到圖片壓縮,面對(duì)這么常用的功能,肯定要嘗試實(shí)現(xiàn)一番。
第一步,node基本配置
這里我們用到的是koa框架,它可是繼express框架之后又一個(gè)更富有表現(xiàn)力、更健壯的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'); // 引入靜態(tài)文件處理
const fs = require('fs'); // 文件系統(tǒng)
const koaBody = require('koa-body'); //文件保存庫
const path = require('path'); // 路徑
2、使用基本配置
let app = new Koa();
let router = new Router();
tinify.key = ''; // 這里需要用到tinify官網(wǎng)的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'],
}));
// 靜態(tài)處理器配置
const home = serve(path.join(__dirname) + '/public/');
app.use(home);
//上傳文件限制
app.use(koaBody({
multipart: true,
formidable: {
maxFileSize: 200 * 1024 * 1024 // 設(shè)置上傳文件大小最大限制,默認(rèn)2M
}
}));
3、tinify官網(wǎng)的key獲取方式
輸入你名字跟郵箱,點(diǎn)擊 Get your API key , 就可以了。
注意: 這個(gè)API一個(gè)月只能有500次免費(fèi)的機(jī)會(huì),不過我覺得應(yīng)該夠了。
第二步,詳細(xì)接口配置
我們要實(shí)現(xiàn)圖片上傳以及壓縮,下面我們將要實(shí)現(xiàn)。
1、上傳圖片
var new1 = '';
var new2 = '';
// 上傳圖片
router.post('/uploadPic', async (ctx, next) => {
const file = ctx.request.files.file; // 上傳的文件在ctx.request.files.file
// 創(chuàng)建可讀流
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}`;
//創(chuàng)建可寫流
const upStream = fs.createWriteStream(targetPath);
new1 = targetPath;
new2 = newFilename;
// 可讀流通過管道寫入可寫流
reader.pipe(upStream);
//返回保存的路徑
console.log(newFilename)
ctx.body ="上傳成功"
});
2、壓縮圖片以及定時(shí)刪除圖片
// 壓縮圖片
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()}`)
// 根據(jù)修改時(shí)間判斷做下區(qū)分,以分辨是否更改
if (cur.mtime != prv.mtime) {
console.log(sql + '發(fā)生更新')
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('服務(wù)器運(yùn)行中')
第三步,前臺(tái)頁面配置
實(shí)現(xiàn)了后臺(tái)的配置,那么我們將要展示實(shí)現(xiàn)它,頁面有點(diǎn)low,只是為了實(shí)現(xiàn)基本的功能。
<!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;">上傳進(jìn)度:</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>
總結(jié)
以上所述是小編給大家介紹的Nodejs實(shí)現(xiàn)圖片上傳、壓縮預(yù)覽、定時(shí)刪除功能,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
- vue 使用微信jssdk,調(diào)用微信相冊(cè)上傳圖片功能
- javascript實(shí)現(xiàn)移動(dòng)端上傳圖片功能
- javascript實(shí)現(xiàn)移動(dòng)端 HTML5 圖片上傳預(yù)覽和壓縮功能示例
- Vue + Node.js + MongoDB圖片上傳組件實(shí)現(xiàn)圖片預(yù)覽和刪除功能詳解
- 通過js實(shí)現(xiàn)壓縮圖片上傳功能
- JS+HTML實(shí)現(xiàn)自定義上傳圖片按鈕并顯示圖片功能的方法分析
- js實(shí)現(xiàn)上傳圖片并顯示圖片名稱
- JS實(shí)現(xiàn)壓縮上傳圖片base64長(zhǎng)度功能
- JS+html5實(shí)現(xiàn)異步上傳圖片顯示上傳文件進(jìn)度條功能示例
- JavaScript實(shí)現(xiàn)圖片上傳并預(yù)覽并提交ajax
- Js實(shí)現(xiàn)粘貼上傳圖片的原理及示例
相關(guān)文章
Express + Node.js實(shí)現(xiàn)登錄攔截器的實(shí)例代碼
本篇文章主要介紹了Express + Node.js實(shí)現(xiàn)攔截器的實(shí)例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07
開發(fā)Node CLI構(gòu)建微信小程序腳手架的示例
這篇文章主要介紹了開發(fā)Node CLI構(gòu)建微信小程序腳手架,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
Nodejs高擴(kuò)展性的模板引擎 functmpl簡(jiǎn)介
本文給大家分享的是一款nodejs高擴(kuò)展性的模板引擎functmpl的簡(jiǎn)單介紹以及用法詳解,有需要的小伙伴可以參考下2017-02-02
node使用promise替代回調(diào)函數(shù)
這篇文章主要介紹了node使用promise替代回調(diào)函數(shù),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05
nodejs實(shí)現(xiàn)截取上傳視頻中一幀作為預(yù)覽圖片
這篇文章主要為大家詳細(xì)介紹了nodejs實(shí)現(xiàn)截取上傳視頻中一幀作為預(yù)覽圖片,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
Node.js和Vue的安裝與配置超詳細(xì)步驟(推薦)
使用VUE前端框架開發(fā),需要安裝Node.js和Vue.js,這篇文章主要給大家介紹了關(guān)于Node.js和Vue的安裝與配置超詳細(xì)步驟的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
理解nodejs的stream和pipe機(jī)制的原理和實(shí)現(xiàn)
本篇文章主要介紹了理解nodejs的stream和pipe機(jī)制的原理和實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08
nodejs實(shí)現(xiàn)一個(gè)word文檔解析器思路詳解
這篇文章主要介紹了nodejs實(shí)現(xiàn)一個(gè)word文檔解析器的思路詳解,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-08-08
Node.js+Express+Mysql 實(shí)現(xiàn)增刪改查
這篇文章主要介紹了Node.js+Express+Mysql 實(shí)現(xiàn)增刪改查,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04

