项目中遇到wangEditor配合腾讯cos实现图片上传的问题,查了一圈,大家写的方法都不能解决,最终自己试了出来,记录一下。
1.配置cos
此部分详见cos官网,不再赘述;
2.引入cos
import COS from 'cos-js-sdk-v5'
//配置id和密钥
const cos = new COS({
SecretId:'xxxx',
SecretKey:'xxxxxxxx'
})
3.引入Editor
详见官网
4.在 onCreated中更改配置
onCreated(editor) {
// 一定要用 Object.seal() ,否则会报错
this.editor = Object.seal(editor);
//图片配置
// 自定义上传方法
const customUpload = (file, insertFn) => {
// file 即选中的文件
// 自己实现上传,并得到图片 url alt href
// 最后插入图片
// const url = this.uploadImg(file);
cos.putObject(
{
Bucket: "xxxxx", // 存储桶名称
Region: "ap-chengdu", // 地域
Key: file.name, // 文件名
Body: file, // 要上传的文件对象
StorageClass: "STANDARD", // 上传的模式类型 直接默认 标准模式即可
},
(err, data) => {
if (data?.Location) {
const url = "http://" + data.Location;
insertFn(url);
}
}
);
};
//将定义的上传方法与绑定给editor的uploadImage配置
editor.getMenuConfig("uploadImage").customUpload = customUpload;
},