100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Nodejs实现图片的上传 压缩预览 定时删除。

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

时间:2021-03-15 23:12:56

相关推荐

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>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。