浏览量:3541 最近编辑于:2022-06-15 19:24:48
# Introduction
**Editor.md**富文本编辑器没有自带复制粘贴图片的功能,自己手写了个,支持复制粘贴、拖拽的方式插入编辑器中;并自动上传图片至博客后台的图床,省去了手动上传的麻烦。代码如下:
```javascript
function initPasteDragImg(Editor){
var doc = document.getElementById(Editor.id)
doc.addEventListener('paste', function (event) {
var items = (event.clipboardData || window.clipboardData).items;
var file = null;
if (items && items.length) {
// 搜索剪切板items
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
file = items[i].getAsFile();
break;
}
}
}
else {
console.log("当前浏览器不支持");
return;
}
if (!file) {
console.log("粘贴内容非图片");
return;
}
uploadImg(file,Editor);
});
var dashboard = document.getElementById(Editor.id)
dashboard.addEventListener("dragover", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("dragenter", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("drop", function (e) {
e.preventDefault()
e.stopPropagation()
var files = this.files || e.dataTransfer.files;
uploadImg(files[0],Editor);
})
}
function uploadImg(file,Editor){
var formData = new FormData();
if(file==undefined){
alert("不支持的文件类型!");
return;
}
//var fileName=new Date().getTime()+"."+file.name.split(".").pop();
var fileName = file.name;
if(/\.(png|jpg|jpeg|gif|bmp|ico|webp)$/.test(fileName)){
}
else{
alert("不支持的文件类型!");
return;
}
formData.append('editormd-image-file', file, fileName);
$.ajax({
url: Editor.settings.imageUploadURL,
type: 'post',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function (msg) {
var success=msg['success'];
if(success==1){
var url=msg["url"];
if(/\.(png|jpg|jpeg|gif|bmp|ico|webp)$/.test(url)){
Editor.insertValue("![image]("+msg["url"]+")");
}else{
Editor.insertValue("[下载附件]("+msg["url"]+")");
}
}else{
alert(msg["message"]);
}
}
});
}
```
![image](/files/album/20210624-2.jpg)
![image](/files/album/20210624-3.jpg)