其他分享
首页 > 其他分享> > koa--批量上传图片

koa--批量上传图片

作者:互联网


const path = require('path');
const fs = require('fs');


//上传图片公共代码块
const _commonCode = (file, ctx) => {

    // 创建可读流
    const reader = fs.createReadStream(file.path);
    //设置目标上传路径
    let target = path.resolve(__dirname, `../public/img/${ctx.request.body.layout_id}`)

    //以layout_id命名的文件夹若不存在,则创建
    if (fs.existsSync(target) === false) {
        fs.mkdirSync(target)
    }
    let filePath = target + `/${file.name}`
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    reader.pipe(upStream);

}



exports.upload = (ctx) => {
    // 上传多个文件
    const files = ctx.request.files.file; // 获取上传文件信息

    const allowExtname = ['.png', '.jpg', '.jpeg', '.webp', '.bmp'];//支持的图片格式
    let filterPic = false;//是否存在不支持的图片格式标识
    const rejectExtname=[]//不支持的图片格式数组

    if (files.length > 1) {
        for (let file of files) {

            const extname = path.extname(file.name);// 获取上传文件拓展名
            if (allowExtname.includes(extname)) {
                _commonCode(file, ctx);//图片格式符合,进行上传
            }else{
                filterPic = true;//图片格式不符合条件,更改标识
                rejectExtname.push(extname)//填充不支持的图片格式数组
            }


        }
    } else {
        const file = ctx.request.files.file;
        const extname = path.extname(file.name);// 获取上传文件拓展名
        if (allowExtname.includes(extname)) {
            _commonCode(file, ctx);//图片格式符合,进行上传
        }else{
            filterPic = true;//图片格式不符合条件,更改标识
            rejectExtname.push(extname) //填充不支持的图片格式数组
        }

    }
  
}



标签:const,批量,koa,图片格式,ctx,extname,file,上传
来源: https://blog.csdn.net/qq_42813491/article/details/101263180