Node.js 实现图片上传压缩

npm下载 响应的组件:

        formidable images fs

下面为封装好的文件,在别处调用

/**
 * 载入公用函数库
 */
// 路径管理
const path = require('path');
// 定义程序根目录
const appPath = path.resolve();
//表单
const formidable = require('formidable');
//图片压缩
const images = require('images');
// 文件管理
const fs = require('fs');


/**
 * 载入私用函数库
 */
// 日志处理
const log = require(appPath + '/utils/log');
// 私有封装函数
const fn = require(appPath + '/utils/function');

/**
 * 获取文件上传的图片路径
* @param {object}req
 * @param {object}res
 * @returns {object} return:文件对象路径
 */
function imageFilePath(req, res) {

    // log.ger('info', req);
    // log.ger('info', res);

    //实例化formidable
    var form = new formidable.IncomingForm();
    //使上传的文件保持原来的文件的扩展名
    form.keepExtensions = true;
    form.multiples = true;
    //指定文件上传的路径 
    form.uploadDir = path.join(appPath + '/', "imageFilePath");
    // 异步捕获处理后的文件名
    return new Promise((resolve, reject) => {
        //转换请求中表单中的数据
        form.parse(req, function (err, fields, files) {
            if (err) {
                //抛出错误
                throw err;
            }
            log.ger('info', '图片上传后的路径--------------------------------------------:');
            log.ger('info', JSON.stringify(files.image.path));
            resolve(files.image.path)
        })
    })
};

/**
 * 处理图片文件压缩
 * @param {object} pathFileName {}图片所在路径
 * @param {int} size 等比缩放图像到多少像素
 * @param {int} quality 图片质量为多少
 * @returns {object} returns 
 */
function explorer(pathFileName, size, quality) {
    log.ger('info', '路径----------' + pathFileName);
    // log.ger('info', fs.readFileSync(pathFileName + "123"));

    try {
        fs.readFileSync(pathFileName);
        if (!size) {
            images(pathFileName)
            .save(appPath + '/imageFilePath/' + fn.timeStamp() + ".jpg", { //Save the image to a file,whih quality 50
                quality: quality //保存图片到文件,图片质量为50
            });
        }else{
            images(pathFileName)
            .size(size)
            .save(appPath + '/imageFilePath/' + fn.timeStamp() + ".jpg", { //Save the image to a file,whih quality 50
                quality: quality //保存图片到文件,图片质量为50
            });
        }
        return appPath + '/imageFilePath/' + fn.timeStamp() + ".jpg";
        // let fileName = pathFileName.split("\\");
        // log.ger('info', '路径----------' + fileName);



    } catch (error) {
        log.ger('info', error);
        return "error"
    }



    // fs.readdir(path, function (err, files) {
    //     //err 为错误 , files 文件名列表包含文件夹与文件
    //     if (err) {
    //         console.log('error:\n' + err);
    //         return;
    //     }

    //     files.forEach(function (file) {
    //         fs.stat(path + '/' + file, function (err, stat) {
    //             if (err) { console.log(err); return; }
    //             if (stat.isDirectory()) {
    //                 // 如果是文件夹遍历
    //                 explorer(path + '/' + file);
    //             } else {
    //                 // 读出所有的文件
    //                 console.log('文件名:' + path + '/' + file);
    //                 var name = path + '/' + file;
    //                 if (name == fileName) {
    //                     var outName = path + '/' + 'another_' + file

    //                     images(name)

    //                         .save(outName, { //Save the image to a file,whih quality 50
    //                             quality: 60 //保存图片到文件,图片质量为50
    //                         });
    //                 }
    //             }
    //         });

    //     });

    // });
}


/**
 * 对外出口配置
 * 
 */
module.exports = {
    imageFilePath,
    explorer
}

在别处直接引入调用

let enter = async function (request, response) {
    // 使用过滤器验证数据头和数据类型
    let VHDData = await ft.VUD(request, response, filterData = { "headers": "multipart/form-data", "token": false, });
    if (VHDData.state == 0) {
        switch (VHDData.type) {
            case "imageCompression":
                //文件上传
                let filePath = await imageCompression.imageFilePath(request, response);
                // //压缩图片
                let newFile = await imageCompression.explorer(filePath, 100, 10);
                //返回结果
                res.send(request, response, msg.type("ok", "ok",newFile));
                break;

            default:
                break;
        }
    }
}

// 导出接口
module.exports = { enter };

猜你喜欢

转载自blog.csdn.net/weixin_48188065/article/details/119821770