说明:在使用cool-admin这个低代码平台时,发现官方的cos上传插件有问题,总是报错 substring,故自己找解决方案,修改本地的upload方法改为云端上传。
解决方案:
- 安装腾讯云cos的nodeJS SDK
pnpm i cos-nodejs-sdk-v5
- 在
admin-midway/src/modules/plugin/hooks/upload
目录下新建工具文件upload_cos.ts
内容如下:
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 || ''; this.cos = new COS({SecretId: 'xxxxxx', SecretKey: 'xxxxxx', });}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 {const parsedUrl = new URL(imageUrl);const pathname = parsedUrl.pathname;const imageName = pathname.split('/').pop() || '';return imageName;}
}export default CosUtil;
- 修改上述目录下的
index.ts
文件:
import CosUtil from './upload_cos';
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);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.ts
中domain
参数将会失效
hooks: {upload: {domain: ``,},},
由于是非正式项目,存储桶访问权限设置的是公有读写,不需要做身份验证。如有需要可查看官方文档:设置存储桶访问权限