需求:粘贴上传图片,截图工具,右键粘贴,或者ctrl+v粘贴

方法1:可直接套用富文本框的图片上传功能,完成复制粘贴

缺点:麻烦,样式难控制

方法2:用原生js完成,以下案例基于此,样式请自己动手调整

用js完成请注意收下几点:

1、前端传回去给后台是base64流,后台要将接收的base64转换成图片保存,记住不是二进制流,是base64位

2、editorWenban是可编辑的文本框,用以复制粘贴图片,tar_box是用来曾现图片的

前端代码如下:

<!DOCTYPE html>
<html lang="UTF-8">
<head>
<meta charset="UTF-8">
<title>测试测试</title>
</head> <style>
body {
display: -webkit-flex;
display: flex;
-webkit-justify-content: center;
justify-content: center;
}
#tar_box {
width: 500px;
height: 500px;
border: 1px solid red;
} #editorWenban img{
display: none;
} #tar_box img{
width: 120px;
height: 120px;
margin:20px;
border: 1px solid #5a7710;
}
</style> <body> <div contenteditable style="width: 100px;height: 100px; border:1px solid" id="editorWenban">
</div> <div id="tar_box">
<!--<img src="" style=""/>-->
</div> <script>
document.addEventListener('paste', function (event) {
console.log(event)
var isChrome = false;
if ( event.clipboardData || event.originalEvent ) {
//not for ie11 某些chrome版本使用的是event.originalEvent
var clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
if ( clipboardData.items ) {
// for chrome
var items = clipboardData.items,
len = items.length,
blob = null;
isChrome = true;
//items.length比较有意思,初步判断是根据mime类型来的,即有几种mime类型,长度就是几(待验证)
//如果粘贴纯文本,那么len=1,如果粘贴网页图片,len=2, items[0].type = 'text/plain', items[1].type = 'image/*'
//如果使用截图工具粘贴图片,len=1, items[0].type = 'image/png'
//如果粘贴纯文本+HTML,len=2, items[0].type = 'text/plain', items[1].type = 'text/html'
// console.log('len:' + len);
// console.log(items[0]);
// console.log(items[1]);
// console.log( 'items[0] kind:', items[0].kind );
// console.log( 'items[0] MIME type:', items[0].type );
// console.log( 'items[1] kind:', items[1].kind );
// console.log( 'items[1] MIME type:', items[1].type ); //阻止默认行为即不让剪贴板内容在div中显示出来
event.preventDefault(); //在items里找粘贴的image,据上面分析,需要循环
for (var i = 0; i < len; i++) {
if (items[i].type.indexOf("image") !== -1) {
// console.log(items[i]);
// console.log( typeof (items[i])); //getAsFile() 此方法只是living standard firefox ie11 并不支持
blob = items[i].getAsFile();
}
}
if ( blob !== null ) {
var reader = new FileReader();
reader.onload = function (event) {
// event.target.result 即为图片的Base64编码字符串
var base64_str = event.target.result
//可以在这里写上传逻辑 直接将base64编码的字符串上传(可以尝试传入blob对象,看看后台程序能否解析)
uploadImgFromPaste(base64_str, 'paste', isChrome);
}
reader.readAsDataURL(blob);
}
} else {
//for firefox
setTimeout(function () {
//设置setTimeout的原因是为了保证图片先插入到div里,然后去获取值
var imgList = document.querySelectorAll('#editorWenban img'),
len = imgList.length,
src_str = '',
i;
for ( i = 0; i < len; i ++ ) {
if ( imgList[i].className !== 'my_img' ) {
//如果是截图那么src_str就是base64 如果是复制的其他网页图片那么src_str就是此图片在别人服务器的地址
src_str = imgList[i].src;
}
}
uploadImgFromPaste(src_str, 'paste', isChrome); //var box = document.getElementById("#editorWenban");
//找到子元素
//var img=document.getElementsByTagName("#editorWenban img");
//console.log("imgimgimgimg",img)
//box.removeChild(img);
}, 1); }
} else {
//for ie11
setTimeout(function () { //document.getElementById("#editorWenban")
var imgList = document.querySelectorAll('#editorWenban img'),
len = imgList.length,
src_str = '',
i;
for ( i = 0; i < len; i ++ ) {
if ( imgList[i].className !== 'my_img' ) {
src_str = imgList[i].src;
}
}
uploadImgFromPaste(src_str, 'paste', isChrome);
}, 1);
}
}) function uploadImgFromPaste (file, type, isChrome) {
console.log("file=============",file)
var formData = new FormData();
formData.append('imgByte', file);
formData.append('submission-type', type); var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://127.0.0.1:8555/weChatHandleTask/saveToImgByStr',true);
xhr.onload = function () {
if ( xhr.readyState === 4 ) {
if ( xhr.status === 200 ) { var data = xhr.responseText;
var tarBox = document.getElementById('tar_box');
var img = document.createElement('img');
img.className = 'my_img';
img.src = 'http://127.0.0.1:8555/test/'+data;
//ie不生效,所以直接在样式中测试
img.style = 'width: 120px; height: 120px; margin:20px;border: 1px solid #5a7710;';
tarBox.appendChild(img); } else {
console.log( xhr.statusText );
}
};
};
xhr.onerror = function (e) {
console.log( xhr.statusText );
}
xhr.send(formData);
} </script> </body>
</html>

后台代码是springboot写的,如下:

/**
* 将接收的base64转换成图片保存
*
* @param imgByte
* base64数据
* @param cardNum
* 号码
* @return 成功返回图片保存路径,失败返回false
*/
@RequestMapping("/saveToImgByStr")
@ResponseBody
public Object saveToImgByStr(String imgByte, String cardNum, HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("imgByte====="+imgByte);
String destDir = "F:\\ScgStaticPath\\test"; if(imgByte.indexOf("data:image/png;base64") > -1){
imgByte=imgByte.replaceAll("data:image/png;base64,","");
BASE64Decoder decoder = new BASE64Decoder();
byte[] imageByte = null;
try{
imageByte = decoder.decodeBuffer(imgByte);
for (int i = 0; i < imageByte.length; ++i) {
// 调整异常数据
if (imageByte[i] < 0) {
imageByte[i] += 256;
}
}
} catch (Exception e) {
e.printStackTrace();
} if (imageByte.length>0) {
try {
//获取文件上传的真实路径
//String uploadPath = request.getSession().getServletContext().getRealPath("/"); SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
String createNewDirStr = fmt.format(new Date()); //保存文件的路径
String filepath = destDir + File.separator + createNewDirStr; File destfile = new File (filepath); if (!destfile.exists()) {
destfile.mkdirs();
}
//文件新名称
String fileNameNew = getFileNameNew() + ".png";
File f = new File(destfile.getAbsoluteFile() + File.separator + fileNameNew);
// 将字符串转换成二进制,用于显示图片
// 将上面生成的图片格式字符串 imgStr,还原成图片显示
InputStream in = new ByteArrayInputStream(imageByte);
FileOutputStream fos = new FileOutputStream(f);
// BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] buf = new byte[1024];
int length;
length = in.read(buf, 0, buf.length); while (length != -1) {
fos.write(buf,0,length);
length = in.read(buf);
}
fos.flush();
fos.close();
in.close();
//String lastpath = filepath + File.separator + fileNameNew;
String lastpath = createNewDirStr + File.separator + fileNameNew;
System.out.println("返回图片路径:" + lastpath);
return lastpath; } catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}else{ ServletInputStream inputStream = request.getInputStream(); //获取文件上传的真实路径
//String uploadPath = request.getSession().getServletContext().getRealPath("/"); SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
String createNewDirStr = fmt.format(new Date()); //保存文件的路径
String filepath = destDir + File.separator + createNewDirStr;
File destfile = new File( filepath);
if (!destfile.exists()) {
destfile.mkdirs();
}
//文件新名称
String fileNameNew = getFileNameNew() + ".png";
File f = new File(destfile.getAbsoluteFile() + File.separator + fileNameNew);
if (!f.exists()) {
OutputStream os = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(os); byte[] buf = new byte[1024];
int length;
length = inputStream.read(buf, 0, buf.length); while (length != -1) {
bos.write(buf, 0, length);
length = inputStream.read(buf);
}
bos.close();
os.close();
inputStream.close();
//String lastpath = filepath + File.separator + fileNameNew;
String lastpath = createNewDirStr + File.separator + fileNameNew;
System.out.println("返回图片路径:" + lastpath);
return lastpath;
}
} return false;
} /**
* 为文件重新命名,命名规则为当前系统时间毫秒数
*
* @return string
*/
private String getFileNameNew() {
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return fmt.format(new Date());
} /**
* 以当前日期为名,创建新文件夹
*
* @return
*/
private String createNewDir() {
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(new Date());
}

测试完成效果图:

原生js复制粘贴上传图片前后台代码,兼容firebox,chrome, ie11,亲测有效的更多相关文章

  1. 让微信内置浏览器兼容clipboard.js 复制粘贴 ios 安卓

    <!--js copy事件--><script type="text/javascript" src="/static/js/clipboard.min ...

  2. 原生JS实现购物车结算功能代码+zepto版

    html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3 ...

  3. 设为首页 和 收藏本站js代码 兼容IE,chrome,ff

    设为首页 和 收藏本站js代码 兼容IE,chrome,ff //设为首页 function SetHome(obj,url){ try{ obj.style.behavior='url(#defau ...

  4. 基于原生js的返回顶部组件,兼容主流浏览器

    基于原生js的返回顶部插件,兼容IE8及以上.FF.chrome等主流浏览器. js文件中封装了getScrollTop()和changeScrollTop()函数分别用于获取滚动条滚动的高度和修改滚 ...

  5. js 复制粘贴功能记录

    最近工作中需要在前端页面中使用代码完成剪贴板的读写,网上搜索了下相应的资料,记录下... 这个功能有两个办法一个是js方式,一个是使用flash 一.JS方法 1.复制 首先复制的过程分为两步曲,无论 ...

  6. js本地图片预览代码兼容所有浏览器

    html代码 <div id="divPreview" style="width: 160px; height: 170px"><img id ...

  7. 黄聪:原生js的音频播放器,兼容pc端和移动端(原创)

    更新时间:2018/9/3 下午1:32:54 更新说明:添加音乐的loop设置和ended事件监听 loop为ture的时候不执行ended事件 1 2 3 4 5 6 7 8 9 10 11 12 ...

  8. mybatis自动生成代码插件mybatis-generator使用流程(亲测可用)

    mybatis-generator是一款在使用mybatis框架时,自动生成model,dao和mapper的工具,很大程度上减少了业务开发人员的手动编码时间 坐着在idea上用maven构建spri ...

  9. JS input文本框禁用右键和复制粘贴功能的代码

    代码如下: function click(e) { if (document.all) { ||||) { oncontextmenu='return false'; } } if (document ...

随机推荐

  1. java中的基本数据类型转换

    Java 中的 8 种基本数据类型,以及它们的占内存的容量大小和表示的范围,如下图所示: 重新温故了下原始数据类型,现在来解释下它们之间的转换关系. 自动类型转换 自动类型转换是指:数字表示范围小的数 ...

  2. Lambda入门,看这一篇幅就够了

    jdk1.8中的lambda表达式学习笔记 一.引入一个例子 我们写一个多线程的例子,如下:采用实现Runable接口的方式 package cn.lyn4ever.lambda; public cl ...

  3. X86架构CPU常识(主频,外频,FSB,cpu位和字长,倍频系数,缓存,CPU扩展指令集,CPU内核和I/O工作电压,制造工艺,指令集,超流水线与超标量)

    1.主频 主频也叫时钟频率,单位是MHz,用来表示CPU的运算速度. CPU的主频=外频×倍频系数.很多人认为主频就决定着CPU的运行速度,这不仅是个片面的,而且对于服务器来讲,这个认识也出现了偏差. ...

  4. 第三章 学习Shader所需的数学基础(1)

    1. 笛卡尔坐标系 在游戏中,我们使用的数学大部分都是为了计算位置.距离和角度等变量.而这些就算大部分是在笛卡尔坐标系下进行的. 1.1 二维笛卡尔坐标系 一个二维笛卡尔坐标系包含了两个部分的信息 1 ...

  5. SwiftyUserDefaults-封装系统本地化的框架推荐

    // // ViewController.swift // Test4SwiftyUserDefaults // Copyright © 2017年. All rights reserved. // ...

  6. ASCII, Unicode, UTF-8

    (本文参考:http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf-8.html) 1. ASCII码 我们知道,在计算机内部,所有的 ...

  7. RAC环境查询JOB正在运行的信息

    需求: 客户环境12.2.0.1,三节点RAC需要,将一个正在运行的Job session kill掉, 但是通过DBA_JOBS_RUNNING发现,无法发现其它实例运行的JOB,因此需要登陆多台实 ...

  8. 简单理解http协议的特性

    http协议一种数据传输的规范,像我们的在发送数据的时候,我们无法保证发送与接收的类型是一致的,它就保证了我们传输的同一个类型数据. 特性: 1.灵活:我们不管传输什么数据,图片,文件,文字,都可以进 ...

  9. 洛谷 P3420 [POI2005]SKA-Piggy Banks 题解

    蒟蒻的第二篇题解 嗯,直接进入正题 先告诉你们这是并查集,好吧,标签上面有,再来分析这为什么是并查集. 根据题意: 每一个存钱罐能够用相应的钥匙打开或者被砸开,Byteazar已经将钥匙放入到一些存钱 ...

  10. 洛谷 P2388 阶乘之乘 题解

    本蒟蒻又来发题解了QwQ; 看到这个题目,本蒟蒻第一眼就想写打个暴力: 嗯,坏习惯: 但是,动动脑子想一想就知道,普通的的暴力是过不了的: 但是,身为蒟蒻的我,也想不出什么高级的数学方法来优化: 好, ...