cool-admin-midway 使用腾讯云cos上传图片

说明:在使用cool-admin这个低代码平台时,发现官方的cos上传插件有问题,总是报错 substring,故自己找解决方案,修改本地的upload方法改为云端上传。


解决方案:

  1. 安装腾讯云cos的nodeJS SDK
shell 复制代码
pnpm i cos-nodejs-sdk-v5
  1. admin-midway/src/modules/plugin/hooks/upload 目录下新建工具文件upload_cos.ts 内容如下:
typescript 复制代码
const COS: any = require('cos-nodejs-sdk-v5');
import fs = require('fs');

// 定义配置接口
interface CosConfig {
  Bucket?: string;
  Region?: string;
  Prefix?: string;
}

// 定义上传参数接口
interface PutObjectParam {
  key: string;
  buffer: fs.ReadStream | Buffer;
}

class CosUtil {
  private cos;
  private Bucket: string;
  private Region: string;
  private Prefix: string;

  // 构造函数,初始化配置
  constructor(config?: CosConfig) {
    this.Bucket = config?.Bucket || 'mybucket-xxxxxx'; // 存储桶名称
    this.Region = config?.Region || 'ap-guangzhou'; // 存储桶区域
    this.Prefix = config?.Prefix || ''; // 路径前缀

    // 初始化 COS 实例
    this.cos = new COS({
      SecretId: 'xxxxxx', // 密钥id
      SecretKey: 'xxxxxx', // 密钥key
    });
  }

  // 上传文件方法
  public putObject(param: PutObjectParam): Promise<any> {
    return new Promise((resolve, reject) => {
      this.cos.putObject(
        {
          Bucket: this.Bucket, // 必须
          Region: this.Region, // 必须
          Key: param.key, // 必须
          Body: param.buffer, // 必须
        },
        (err: Error, data: any) => {
          if (err) {
            reject(err);
            return;
          }
          resolve(data);
        }
      );
    });
  }
  
  // 提取图片链接中的图片名称
  public getName(imageUrl: string): string {
    // 解析 URL
    const parsedUrl = new URL(imageUrl);

    // 获取路径部分
    const pathname = parsedUrl.pathname;

    // 提取文件名
    const imageName = pathname.split('/').pop() || '';

    return imageName;
  }
}

export default CosUtil;
  1. 修改上述目录下的index.ts文件:
typescript 复制代码
// ... existing code ...
import CosUtil from './upload_cos';
// ... existing code ...

// 修改之前的上传文件代码
   /**
   * 上传文件
   * @param ctx
   * @param key 文件路径
   */
  async upload(ctx: any) {
    const { domain } = this.pluginInfo.config;
    const uploadUtil = new CosUtil();
    try {
      const { key } = ctx.fields;
      if (
        key &&
        (key.includes('..') ||
          key.includes('./') ||
          key.includes('\\') ||
          key.includes('//'))
      ) {
        throw new CoolCommException('非法的key值');
      }
      if (_.isEmpty(ctx.files)) {
        throw new CoolCommException('上传文件为空');
      }
      const basePath = pUploadPath();

      const file = ctx.files[0];
      const extension = file.filename.split('.').pop();
      const name =
        moment().format('YYYYMMDD') + '/' + (key || `${uuid()}.${extension}`);
      const target = path.join(basePath, name);
      const dirPath = path.join(basePath, moment().format('YYYYMMDD'));
      if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath);
      }
      const data = fs.readFileSync(file.data);
      fs.writeFileSync(target, data);
      // 主要变动在这里,key:上传图片的名称(带后缀),buffer:图片的buffer
      const cosResult = await uploadUtil.putObject({
        key: name,
        buffer: data,
      });
      return `https://${cosResult.Location}`;
      
    } catch (err) {
      console.error(err);
      throw new CoolCommException('上传失败' + err.message);
    }
  }

通过以上修改,原来的upload方法及前端组建调用上传方法会得到返回的腾讯云cos存储桶中图片的访问地址,add接口也会把该地址存储到数据库中。

此时admin-node/src/modules/plugin/config.tsdomain参数将会失效

json 复制代码
// 基础插件配置
    hooks: {
      // 文件上传
      upload: {
        // 地址前缀
        domain: ``,
      },
    },

由于是非正式项目,存储桶访问权限设置的是公有读写,不需要做身份验证。如有需要可查看官方文档:设置存储桶访问权限

相关推荐
西猫雷婶3 小时前
STAR-CCM+|雷诺数回顾
云计算
Amy_au12 小时前
Dotnet 项目手动部署到AWS 和Github action CICD 流程总结
云计算·aws
Hi2024021715 小时前
基于阿里云部署 RustDesk 自托管服务器
运维·服务器·阿里云·云计算·远程控制·远程桌面
Tadas-Gao17 小时前
阿里云通义MoE全局均衡技术:突破专家负载失衡的革新之道
人工智能·架构·大模型·llm·云计算
腾讯云大数据20 小时前
IDC MarketScape:腾讯云位居国内生成式AI数据基础设施“领导者”象限
人工智能·云计算·腾讯云
LucianaiB20 小时前
【混元AIGC+腾讯云智能体+首创Coze核心流思维导图MCP】:打造一个文思通-智能写作助手Agent
aigc·腾讯云·ai写作·mcp·腾讯混元大模型aigc
三味神风20 小时前
Linux系统安全加固:构建云计算安全的第一道防线
安全·云计算·系统安全
TG_yunshuguoji1 天前
阿里云国际代理:阿里云的云数据库是什么?
服务器·数据库·安全·阿里云·云计算
lskblog1 天前
Composer安装教程及国内镜像设置(含腾讯云、阿里云镜像)
阿里云·php·腾讯云·laravel·composer
守.护2 天前
云计算学习笔记——日志、SELinux、FTP、systemd篇
linux·云计算·ftp·selinux