前端图片文字复制粘贴功能

自定义右键下拉菜单
复制图片到剪贴板的功能
input框选中ctrl+v或者右键粘贴功能

//右键复制图片的方法 
handleRepeatText() {		
	//图片文字消息复制
	var _this=this;
	writeDataToClipboard();
	async function askWritePermission() { 
		try { 
			const { state } = await navigator.permissions.query({ 
				name: "clipboard-write", 
			}); 
			return state === "granted"; 
		} catch (error) { 
			return false; 
		} 
	}
	//图片转base64 base64转成BLOB 把BLOB类型数据写入剪切板
	function createImageBlob(url) { 
		//图片base64转化
		window.URL = window.URL || window.webkitURL;
		var xhr = new XMLHttpRequest();
		xhr.open("get", url, true);
		// 至关重要
		xhr.responseType = "blob";
		xhr.onload = function () {
			if (this.status == 200) {
				//得到一个blob对象
				var blob = this.response;
				console.log("blob", blob)
				// 至关重要
				let oFileReader = new FileReader();
				oFileReader.onloadend = function (e) {
					// console.log('e.target',e.target.result)
					var result=e.target.result;
					//图片base64转成png形式的
					result='data:image/png;base64,'+result.split(',')[1]
					var dataurl = result;
					//base64转成BLOB方法
					var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = window.atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); 
					while (n--) { 
						u8arr[n] = bstr.charCodeAt(n);
					}
					// console.log("new Blob([u8arr], { type: mime })",new Blob([u8arr], { type: mime }))
					//放入粘贴板
					var imageBlob = new Blob([u8arr], { type: mime });
					try { 
						const item = new ClipboardItem({ 
							[imageBlob.type]: imageBlob, 
						}); 
						navigator.clipboard.write([item]); 
						_this.$message({
							type: "success",
							message: "当前内容已复制到剪切板"
						});
					} catch (error) { 
						console.log("error",error);
						_this.$message({
							type: "error",
							message: "当前内容复制失败"
						});
					}
				};
				oFileReader.readAsDataURL(blob);
			}
		}
		xhr.send();
	} 
	function createTextBlob(text) { 
		return new Blob([text], { type: "text/plain" }); 
	} 
	async function writeDataToClipboard() { 
		if (askWritePermission()) { 
			if (navigator.clipboard && navigator.clipboard.write) { 
				//复制图片
				if(_this.handleContextMenuImg){
					createImageBlob(_this.imgSrc)
				}else{
					//复制文字
					const textBlob = createTextBlob(_this.copyText); 
					try { 
					const item = new ClipboardItem({ 
						[textBlob.type]: textBlob, 
					}); 
					await navigator.clipboard.write([item]); 
					_this.$message({
						type: "success",
						message: "当前内容已复制到剪切板"
					});
					} catch (error) { 
						_this.$message({
							type: "error",
							message: "当前内容复制失败"
						});
					} 

				}
			} 
		} 
	} 
}
//input框获取焦点粘贴事件		
<input  @paste.native="pasteFun($event)"></input>
//消息框右键粘贴或者ctrl+v粘贴功能
pasteFun(e){
	var _this=this;
	//获取clipboardData对象
	var blob='';
	var data=e.clipboardData||window.clipboardData;
	//获取图片内容
	var dateItems=data.items;
	for(var i=0; i<dateItems.length; i++){
		//粘贴文字类型
		if(dateItems[i].kind == "string"){
		}
		//文件类型 图片和文件
		if(dateItems[i].kind == "file"){
			blob=dateItems[i].getAsFile();
			console.log('blob',blob);
			//判断是不是图片,最好通过文件类型判断
			var isImg=(blob&&1)||-1;
			var reader=new FileReader();
			if(isImg>=0){
			//将文件读取为 DataURL
				reader.readAsDataURL(blob);
			}
			//文件读取完成时触发
			reader.onload=function(event){

				//IOS兼容问题
				if(_this.msg && blob.name && navigator.userAgent.indexOf('Mac OS X') !== -1){
					_this.msg=_this.msg.replace(blob.name,'');
				}
				//获取base64流
				var base64_str=event.target.result;
				//代表图片模式
				if(blob.type.indexOf("image/")>-1){
					if(blob.type.indexOf("svg+xml")>-1){
						_this.$message({
							message: '暂不支持svg图片格式进行复制粘贴',
							type: 'error'
						});
						return;
					}
					//粘贴图片内部逻辑处理
					_this.docDialogVisible=true;
					_this.isSendImage=false;
					_this.readImg=base64_str;
					_this.blobFilePaste=blob;
					_this.uploadFileType='image';
					_this.pasteUpdPic=blob.name;
					return;
				}
				//代表文件模式
				if(blob.name.indexOf('.')>-1){
					var nameType=blob.name.split('.').length-1;
					var nameTypeFile=['pdf'];
					if(nameTypeFile.indexOf(blob.name.split('.')[nameType].toLowerCase())>-1){
						//粘贴文件内部逻辑处理
						_this.docDialogVisible=true;
						_this.isSendImage=false;
						_this.uploadFileType='pdf';
						_this.blobFilePaste=blob;
						_this.pasteUpdPic=blob.name;
						return;
					}else{
						_this.$message({
							message: '请选择图片和pdf类型文件进行复制粘贴',
							type: 'error'
						});

					}
				}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值