quill-editor 上传图片
时间: 2023-10-12 13:06:25 浏览: 41
对于 quill-editor 上传图片的问题,一般需要以下几个步骤:
1. 在 quill-editor 中配置 image drop 和 image paste 的 handler;
2. 在 handler 中获取图片并上传到服务器;
3. 上传成功后,将图片地址插入到 quill-editor 中。
下面是具体实现步骤:
1. 在 quill-editor 中配置 handler
```javascript
const quill = new Quill('#editor', {
// ...
modules: {
// ...
toolbar: {
// ...
handlers: {
// 添加 image handler
image: function() {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.setAttribute('style', 'display: none;');
input.addEventListener('change', () => {
const file = input.files[0];
if (/^image\//.test(file.type)) {
this.uploadImage(file);
} else {
console.warn('You could only upload images.');
}
});
document.body.appendChild(input);
input.click();
},
},
},
},
// 添加 uploadImage 方法
uploadImage: function(file) {
const formData = new FormData();
formData.append('file', file);
fetch('/api/upload', {
method: 'POST',
body: formData,
})
.then((response) => response.json())
.then((result) => {
this.insertEmbed(this.getSelection().index, 'image', result.url);
})
.catch((error) => console.error(error));
},
});
```
2. 在后端实现上传接口
根据上面配置的上传接口,在后端需要实现一个类似的接口,接收上传的文件并将其保存在服务器中。具体实现方法和技术栈与后端语言、框架有关,这里不再赘述。