看到一篇文章介绍如何用截图工具将裁切的图片上传,地址为 https://www.cnblogs.com/etoah/p/5140650.html
跟前面的拖拽上传相似。我们需要为容器设置监听事件。这里为粘贴事件 paste
需要注意的是,为了使效果更加明显,我们可以给容器设置聚焦,我们需要将其属性设置为可编辑, 不可编辑状态下也能处理粘贴事件
图片如果想要获取粘贴的图片进行上传,只有直接右键复制的图片才能识别到,ctrl+c的并不能识别.....
contenteditable="true"
在vue中只需要为元素设置多一段事件监听
@paste="paste"
Vue 监听
paste(el) {
handlePaste(el);
}
原生监听如下
contaicner = document.getElementById('contaicner');
//处理目标容器(id)的paste事件
contaicner.addEventListener('paste', function(el) {
handlePaste(el);
}, false);
处理业务如下
function handlePaste(el) {
el.stopPropagation();
el.preventDefault();
if (!el.clipboardData) {
alert('当前浏览器不支持,请更换极速浏览器尝试');
return;
}
if (!el.clipboardData.items) {
alert('没有需要粘贴的数据');
return;
}
for (var i = 0, len = el.clipboardData.items.length; i < len; i++) {
var item = el.clipboardData.items[i];
if (item.kind === "string") {
// type text/plain kind string
item.getAsString(function(str) {
alert('你粘贴了字符串');
})
} else if (item.kind === "file") {
if (item.type.indexOf('image') > -1) {
var reader = new FileReader();
var file = item.getAsFile();
var form_data = new FormData();
form_data.append("file", file);
$.ajaxSetup({
async: false
});
$.ajax({
url: 'upload_image_url',
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response) {
if (response.code == 0) {
doPost(response.data.src);
} else {
alert('图片上传失败,请重试!');
}
}
})
} else {
alert('type:' + item.type);
alert('kind:' + item.kind);
}
}
}
}