vue上传图片文件到服务器,vue如何将quill图片上传到服务器

通过自定义quill图片上传按钮,实现将图片上传服务器,并插入服务器地址。

export default {

name: "editor",

props: ['content'],

data() {

return {

_content: '',

}

},

watch: {

// 监听父组件传递的content值,变化后更新富文本内容

content(newVal, oldVal) {

if (this.quill) {

if (newVal && newVal !== this._content) {

this._content = newVal;

this.quill.clipboard.dangerouslyPasteHTML(newVal);

} else if(!newVal) {

this.quill.setText('');

}

}

}

},

methods: {

uploadToServer(file, callback) {

var xhr = new XMLHttpRequest();

var formData = new FormData();

formData.append('upload', file);

xhr.open('post', this.$ajax.defaults.baseURL + '/upload/blogUpload');

xhr.withCredentials = true;

xhr.responseType = 'json';

xhr.send(formData);

xhr.onreadystatechange = () => {

if (xhr.readyState == 4 && xhr.status == 200) {

callback(xhr.response);

}

};

}

},

mounted() {

// 初始化quill

this.quill = new Quill(this.$refs.editor, {

theme: 'snow',

modules: {

history: {

userOnly: true

},

toolbar: [

['bold', 'italic', 'underline', 'strike'],

['blockquote', 'code-block'],

[{ 'list': 'ordered' }, { 'list': 'bullet' }],

[{ 'script': 'sub' }, { 'script': 'super' }],

[{ 'header': [1, 2, 3, 4, 5, 6, false] }],

[{ 'color': [] }, { 'background': [] }],

[{ 'align': [] }],

['clean'],

['link', 'image', 'video']

],

syntax: true

}

});

// 自定义图片上传

var toolbar = this.quill.getModule('toolbar');

toolbar.addHandler('image', () => {

var fileInput = toolbar.container.querySelector('input.ql-image[type=file]');

if (fileInput == null) {

fileInput = document.createElement('input');

fileInput.setAttribute('type', 'file');

fileInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');

fileInput.classList.add('ql-image');

fileInput.addEventListener('change', () => {

if (fileInput.files != null && fileInput.files[0] != null) {

this.uploadToServer(fileInput.files[0], (res) => {

var range = this.quill.getSelection();

if (range) {

fileInput.value = null;

// 在当前光标位置插入图片

toolbar.quill.insertEmbed(range.index, 'image', this.$ajax.defaults.baseURL + res.file.path);

// 将光标移动到图片后面

toolbar.quill.setSelection(range.index + 1);

}

});

}

});

toolbar.container.appendChild(fileInput);

}

fileInput.click();

});

// 监听富文本变化,更新父组件数据

this.quill.on('text-change', () => {

let html = this.$refs.editor.children[0].innerHTML;

if (html === '

this._content = html;

this.$emit('edit', this._content);

});

}

}

.ql-snow .ql-editor pre.ql-syntax {

background-color: #282c34;

color: #abb2bf;

}

这里面只需要关注自定义图片上传部分即可。

this.$ajax.defaults.baseURL是配置的axios的baseurl,因为我要在本地和线上地址来回切换。

不用太在意,插入自己服务器返回的实际地址就行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值