在开发项目时不可能所有的资源都存放在一个服务器中,这样造成资源加载慢,许多带宽都被图片或者视频的加载占用;七牛云是一个不错的对象存储服务商;
使用
我是配合iview的upload组件使用
<div class="edit_container">
<quill-editor
v-model="articleForm.content"
ref="myQuillEditor"
style="height:300px;"
:options="editorOption"
@change="onEditorChange($event)">
</quill-editor>
</div>
<Upload
ref="uploadpic"
:format="['jpg','jpeg','png','gif']"
:max-size="2048"
accept="image/*"
:before-upload="handleBeforeUpload1"
action="//jsonplaceholder.typicode.com/posts/">
<Button style="display:none" id="picFile"></Button>
</Upload>
computed: {
editor() {
return this.$refs.myQuillEditor.quill;
},
},
替换点击事件
把quill-editor工具栏中的图片点击事件替换掉,一点就会触发upload组件;
mounted(){
this.init()
var vm =this
var imgHandler = async function(image) {
vm.addImgRange = vm.$refs.myQuillEditor.quill.getSelection()
if (image) {
let fileInput = document.getElementById('picFile') //隐藏的file文本ID
fileInput.click() //加一个触发事件
}
}
vm.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("image", imgHandler)
}
上传回显
handleBeforeUpload1 (file) {
if(file){
if((file.size / 1024) > 2048){
this.$Notice.error({
title: '图片超过2M'
});
return false;
}else{
this.pic = file
this.getUploadToken()
}
}
return false;
},
async getUploadToken(iov){
let res = await this.$axios.get('/api/uploadToken')//获取上传凭证
if(res.data.code == 0){
this.$router.push('/')
}else if(res.data.code == 1){
let file = this.pic
//以下为七牛云的配置
let putExtra = {
fname: file,
params: {},
mimeType: ["image/png", "image/jpeg", "image/gif","image/jpeg"]
};
let config = {
useCdnDomain: true,
};
let that = this
let observe = {
next () {}, //这个是传输过程
error (err) { //出错处理
if(err){
that.$Notice.error({
title: '图片上传失败'
})
}
},
complete (res) {
//完成后的操作
//上传成功以后会返回key 和 hash key就是文件名了!
if(res){
let picUrl = `http://q5knt7671.bkt.clouddn.com/${res.key}`
//返回key,拼接完整url
let quill = that.$refs.myQuillEditor.quill
//光标到富文本编辑器,不然会报'index'错误
quill.focus()
// 获取光标所在位置
let length = quill.getSelection().index;
that.imgUS.push(res.key)
// 插入图片 picUrl 为服务器返回的图片地址
quill.insertEmbed(length, 'image', picUrl)
// 调整光标到最后
quill.setSelection(length + 1)
}
}
};// observe
let observable = qiniu.upload(file, this.pic.lastModified, res.data.token, putExtra, config)
//七牛云上传,具体看七牛云文档,JavaScript SDK文档;
let subscription = observable.subscribe(observe) // 这样传参形式也可以
}
},
注意:要先入包啊,比如quill-editor
,qiniu
等,如果没有意外的话,应该成功了。同意如果要修改工具栏的video也是一样的,只要把image
改为video
就行;