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'); //文件保存庫(kù)
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ì),不過(guò)我覺(jué)得應(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);
// 修改文件的名稱(chēng)
var myDate = new Date();
var newFilename = myDate.getTime() + '.' + file.name.split('.')[1];
var targetPath = path.join(__dirname, './public/images/') + `${newFilename}`;
//創(chuàng)建可寫(xiě)流
const upStream = fs.createWriteStream(targetPath);
new1 = targetPath;
new2 = newFilename;
// 可讀流通過(guò)管道寫(xiě)入可寫(xiě)流
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)頁(yè)面配置
實(shí)現(xiàn)了后臺(tái)的配置,那么我們將要展示實(shí)現(xiàn)它,頁(yè)面有點(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>
作者:Vam的金豆之路
主要領(lǐng)域:前端開(kāi)發(fā)
我的微信:maomin9761
微信公眾號(hào):前端歷劫之路