Vue解析剪切板图片并实现发送功能

简介: Vue解析剪切板图片并实现发送功能

每一份坚持都是成功的累积,只要相信自己,总会遇到惊喜😜


前言


我们在使用QQ进行聊天时,从别的地方Ctrl+C一张图片,然后在聊天窗口Ctrl+V,QQ就会将你刚才复制的图片粘贴到即将发送的消息容器里,按下Enter键,这张图片将会发送出去。接下来跟各位开发者分享下这项功能在Vue中如何来实现。


实现思路


  • 页面挂载时监听剪切板粘贴事件
  • 监听文件流
  • 读取文件流中的数据
  • 创建img标签
  • 将获取到的base64码赋值到img标签的src属性
  • 将生成的img标签append到即将发送的消息容器里
  • 监听回车事件
  • 获取可编辑div容器中的所有子元素
  • 遍历获取到的元素,找出img元素
  • 判断当前img元素是否有alt属性(表情插入时有alt属性),
  • 如果没有alt属性当前元素就是图片
  • 将base64格式的图片转成文件上传至服务器
  • 上传成功后,将服务器返回的图片地址推送到websocket服务
  • 客户端收到推送后,渲染页面


实现过程


本片文章主要讲解剪切板图片的解析以及将base64图片转换成文件上传至服务器,下方代码中的axios的封装以及websocket的配置与使用可参考我的另外两篇文章:Vue合理配置axios并在项目中进行实际应用Vue合理配置WebSocket并实现群聊


  • 监听剪切板事件(mounted生命周期中),将图片渲染到即将发送到消息容器里


const that = this;
document.body.addEventListener('paste', function (event) {
   // 自己写的一个全屏加载插件,文章地址:https://juejin.im/post/5e3307145188252c30002fa7
   that.$fullScreenLoading.show("读取图片中");
   // 获取当前输入框内的文字
   const oldText = that.$refs.msgInputContainer.textContent;
   // 读取图片
   let items = event.clipboardData && event.clipboardData.items;
   let file = null;
   if (items && items.length) {
       // 检索剪切板items
       for (let i = 0; i < items.length; i++) {
           if (items[i].type.indexOf('image') !== -1) {
               file = items[i].getAsFile();
               break;
          }
      }
  }
   // 预览图片
   const reader = new FileReader();
   reader.onload = function(event) {
       // 图片内容
       const imgContent = event.target.result;
       // 创建img标签
       let img = document.createElement('img');//创建一个img
       // 获取当前base64图片信息,计算当前图片宽高以及压缩比例
       let imgObj = new Image();
       let imgWidth = "";
       let imgHeight = "";
       let scale = 1;
       imgObj.src = imgContent;
       imgObj.onload = function() {
           // 计算img宽高
           if(this.width<400){
               imgWidth = this.width;
               imgHeight = this.height;
          }else{
               // 输入框图片显示缩小10倍
               imgWidth = this.width/10;
               imgHeight = this.height/10;
               // 图片宽度大于1920,图片压缩5倍
               if(this.width>1920){
                   // 真实比例缩小5倍
                   scale = 5;
              }
          }
           // 设置可编辑div中图片宽高
           img.width = imgWidth;
           img.height = imgHeight;
           // 压缩图片,渲染页面
           that.compressPic(imgContent,scale,function (newBlob,newBase) {
               // 删除可编辑div中的图片名称
               that.$refs.msgInputContainer.textContent = oldText;
               img.src = newBase; //设置链接
               // 图片渲染
               that.$refs.msgInputContainer.append(img);
               that.$fullScreenLoading.hide();
          });
      };
  };
   reader.readAsDataURL(file);
});


  • base64图片压缩函数

 

// 参数: base64地址,压缩比例,回调函数(返回压缩后图片的blob和base64)
   compressPic:function(base64, scale, callback){
       const that = this;
       let _img = new Image();
       _img.src = base64;
       _img.onload = function() {
           let _canvas = document.createElement("canvas");
           let w = this.width / scale;
           let h = this.height / scale;
           _canvas.setAttribute("width", w);
           _canvas.setAttribute("height", h);
           _canvas.getContext("2d").drawImage(this, 0, 0, w, h);
           let base64 = _canvas.toDataURL("image/jpeg");
           // 当canvas对象的原型中没有toBlob方法的时候,手动添加该方法
           if (!HTMLCanvasElement.prototype.toBlob) {
               Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
                   value: function (callback, type, quality) {
                       let binStr = atob(this.toDataURL(type, quality).split(',')[1]),
                           len = binStr.length,
                           arr = new Uint8Array(len);
                       for (let i = 0; i < len; i++) {
                           arr[i] = binStr.charCodeAt(i);
                      }
                       callback(new Blob([arr], {type: type || 'image/png'}));
                  }
              });
          }else{
               _canvas.toBlob(function(blob) {
                   if(blob.size > 1024*1024){
                       that.compressPic(base64, scale, callback);
                  }else{
                       callback(blob, base64);
                  }
              }, "image/jpeg");
          }
      }
  }


  • 完善消息发送函数,获取输入框里的所有子元素,找出base64图片将其转为文件并上传至服务器(此处需要注意:base64转文件时,需要用正则表达式删掉base64图片的前缀),将当前图片地址推送至websocket服务。

对下述代码有不理解的地方,可阅读我的另一篇文章:Vue实现图片与文字混输


sendMessage: function (event) {
   if (event.keyCode === 13) {
       // 阻止编辑框默认生成div事件
       event.preventDefault();
       let msgText = "";
       // 获取输入框下的所有子元素
       let allNodes = event.target.childNodes;
       for (let item of allNodes) {
           // 判断当前元素是否为img元素
           if (item.nodeName === "IMG") {
               if (item.alt === "") {
                   // 是图片
                   let base64Img = item.src;
                   // 删除base64图片的前缀
                   base64Img = base64Img.replace(/^data:image\/\w+;base64,/, "");
                   //随机文件名
                   let fileName = (new Date()).getTime() + ".jpeg";
                   //将base64转换成file
                   let imgFile = this.convertBase64UrlToImgFile(base64Img, fileName, 'image/jpeg');
                   let formData = new FormData();
                   // 此处的file与后台取值时的属性一样,append时需要添加文件名,否则一直blob
                   formData.append('file', imgFile, fileName);
                   // 将图片上传至服务器
                   this.$api.fileManageAPI.baseFileUpload(formData).then((res) => {
                       const msgImgName = `/${res.fileName}/`;
                       // 消息发送: 发送图片
                       this.$socket.sendObj({
                           msg: msgImgName,
                           code: 0,
                           username: this.$store.state.username,
                           avatarSrc: this.$store.state.profilePicture,
                           userID: this.$store.state.userID
                      });
                       // 清空输入框中的内容
                       event.target.innerHTML = "";
                  });
              } else {
                   msgText += `/${item.alt}/`;
              }
          } else {
               // 获取text节点的值
               if (item.nodeValue !== null) {
                   msgText += item.nodeValue;
              }
          }
      }
       // 消息发送: 发送文字,为空则不发送
       if (msgText.trim().length > 0) {
           this.$socket.sendObj({
               msg: msgText,
               code: 0,
               username: this.$store.state.username,
               avatarSrc: this.$store.state.profilePicture,
               userID: this.$store.state.userID
          });
           // 清空输入框中的内容
           event.target.innerHTML = "";
      }
  }
}


  • base64图片转flie


// base64转file
convertBase64UrlToImgFile: function (urlData, fileName, fileType) {
   // 转换为byte
   let bytes = window.atob(urlData);
   // 处理异常,将ascii码小于0的转换为大于0
   let ab = new ArrayBuffer(bytes.length);
   let ia = new Int8Array(ab);
   for (let i = 0; i < bytes.length; i++) {
       ia[i] = bytes.charCodeAt(i);
  }
   // 转换成文件,添加文件的type,name,lastModifiedDate属性
   let blob = new Blob([ab], {type: fileType});
   blob.lastModifiedDate = new Date();
   blob.name = fileName;
   return blob;
}


  • axios文件上传接口的封装(注意:需要设置"Content-Type":"multipart/form-data"})


/*
* 文件管理接口
* */
import services from '../plugins/axios'
import base from './base'; // 导入接口域名列表
const fileManageAPI = {
   // 单文件上传
   baseFileUpload(file){
       return services._axios.post(`${base.lkBaseURL}/uploads/singleFileUpload`,file,{headers:{"Content-Type":"multipart/form-data"}});
  }
};
export default fileManageAPI;


  • 解析websocket推送的消息


// 消息解析
messageParsing: function (msgObj) {
   // 解析接口返回的数据并进行渲染
   let separateReg = /(\/[^/]+\/)/g;
   let msgText = msgObj.msgText;
   let finalMsgText = "";
   // 将符合条件的字符串放到数组里
   const resultArray = msgText.match(separateReg);
   if (resultArray !== null) {
       for (let item of resultArray) {
           // 删除字符串中的/符号
           item = item.replace(/\//g, "");
           // 判断是否为图片: 后缀为.jpeg
           if(this.isImg(item)){
               // 解析为img标签
               const imgTag = `<img src="${base.lkBaseURL}/upload/image/${item}" alt="聊天图片">`;
               // 替换匹配的字符串为img标签:全局替换
               msgText = msgText.replace(new RegExp(`/${item}/`, 'g'), imgTag);
          }
      }
       finalMsgText = msgText;
  } else {
       finalMsgText = msgText;
  }
   msgObj.msgText = finalMsgText;
   // 渲染页面
   this.senderMessageList.push(msgObj);
   // 修改滚动条位置
   this.$nextTick(function () {
       this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight;
  });
}


  • 判断当前字符串是否为有图片后缀


// 判断是否为图片
isImg: function (str) {
   let objReg = new RegExp("[.]+(jpg|jpeg|swf|gif)$", "gi");
   return objReg.test(str);
}


踩坑记录


  • 直接将base64格式的图片通过websocket发送至服务端


结果很明显,服务端websocket服务报错,报错原因:内容超过最大长度。


  • 前端通过post请求将base64码传到服务端,服务端直接将base64码解析为图片保存至服务器


从下午2点折腾到晚上6点,一直在找Java解析base64图片存到服务器的方案,最终选择了放弃,采用了前端转换方式,这里的问题大概是前端传base64码到后端时,http请求会进行转义,导致后端解析得到的base64码是错误的,所以一直没有成功。


  • 项目地址:点击下方阅读原文进行查看


写在最后


  • 文中如有错误,欢迎在原文评论区指正,如果这篇文章帮到了你,欢迎点赞和关注😊


相关文章
|
10月前
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
785 2
|
9月前
|
缓存 JavaScript
vue中的keep-alive问题(2)
vue中的keep-alive问题(2)
661 137
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
1257 0
|
JavaScript UED
用组件懒加载优化Vue应用性能
用组件懒加载优化Vue应用性能
|
9月前
|
监控
新功能上线:云解析DNS-重点域名监控功能发布
新功能上线:云解析DNS-重点域名监控功能发布
|
JavaScript 前端开发 开发者
Vue 自定义进度条组件封装及使用方法详解
这是一篇关于自定义进度条组件的使用指南和开发文档。文章详细介绍了如何在Vue项目中引入、注册并使用该组件,包括基础与高级示例。组件支持分段配置(如颜色、文本)、动画效果及超出进度提示等功能。同时提供了完整的代码实现,支持全局注册,并提出了优化建议,如主题支持、响应式设计等,帮助开发者更灵活地集成和定制进度条组件。资源链接已提供,适合前端开发者参考学习。
788 17
|
人工智能 JSON JavaScript
VTJ.PRO 首发 MasterGo 设计智能识别引擎,秒级生成 Vue 代码
VTJ.PRO发布「AI MasterGo设计稿识别引擎」,成为全球首个支持解析MasterGo原生JSON文件并自动生成Vue组件的AI工具。通过双引擎架构,实现设计到代码全流程自动化,效率提升300%,助力企业降本增效,引领“设计即生产”新时代。
822 1
|
12月前
|
JavaScript 安全
在 Vue 中,如何在回调函数中正确使用 this?
在 Vue 中,如何在回调函数中正确使用 this?
576 0
|
JavaScript 前端开发 UED
Vue 表情包输入组件实现代码及详细开发流程解析
这是一篇关于 Vue 表情包输入组件的使用方法与封装指南的文章。通过安装依赖、全局注册和局部使用,可以快速集成表情包功能到 Vue 项目中。文章还详细介绍了组件的封装实现、高级配置(如自定义表情列表、主题定制、动画效果和懒加载)以及完整集成示例。开发者可根据需求扩展功能,例如 GIF 搜索或自定义表情上传,提升用户体验。资源链接提供进一步学习材料。
866 1
|
存储 前端开发 JavaScript
为什么我不再用Vue,改用React?
当我走进现代前端开发行业的时候,我做了一个每位开发人员都要做的决策:选择一个合适的框架。当时正逢 jQuery 被淘汰,前端开发者们不再用它编写难看的、非结构化的老式 JavaScript 程序了。

推荐镜像

更多
  • DNS