文件上传压缩

Category:

Tags:

文件上传压缩

1. 前端调用

2. 后端实现(tinily)

上传文件接口

text
// 上传文件 userRouter.post(  "/file",  datalize([filed("image").required()]),  uploadFileError,  checkSize,  verifyAuth,  // checkId,  // deleteOldFile,  saveGlobalFile,  uploadFile );

其他中间件见名思意,实现靠 saveGlobalFile

text
// tinyPng获取key const tinify = require("tinify"); tinify.key = "1Gvd*************fj48WZ"; ​ const saveGlobalFile = async (ctx, next) => {  // 由于内部基于回调方式实现,所以手动构造promise  async function wait() {    return new Promise((resolve) => {      tinify       .fromBuffer(ctx.file.buffer)       .toBuffer(async function (err, resultData) {          if (err) throw err;          resolve(resultData);       });   }); }  // 从上层构造的file对象解析畜buffer,通过tinify讲buffer转换成新的 buffer 存入文件 实现压缩  const resultData = await wait();  const filename =    "image-" +    ctx.file.size +   (Date.now() + "").slice(0, 10) +    `.${ctx.file.mimetype.split("/")[1]}`;  fs.writeFileSync(    path.resolve(__dirname, "../uploads/image", filename),    resultData );  // 暴露信息做sql操作  ctx.request.body.extendname = ctx.file.mimetype;  ctx.request.body.filepath = `/images/${filename}`;  await next(); };

3. 静态托管暴露文件

text
const koaStatic = require("koa-static"); app.use(koaStatic("./src/uploads/")); ​