当前位置: 首页 > news >正文

el-upload照片墙自定义上传多张图片(手动一次性上传多张图片)包含图片回显,删除

需求:el-upload照片墙自定义上传多张图片(手动一次性上传多张图片)包含图片回显,删除,预览,在网上看了很多,都没有说怎么把数据转为file格式的,找了很久最终实现,

难点:怎么把接口获取到的图片转为file格式,如果不是file格式的话,那么后端无法识别,并且还要携带额外的参数

1.调用接口获取已上传图片,格式如下

 获取到数据后,进行回显(调用接口我就不写了,我只写数据获取到后转为file格式)

fileImgList:用于照片回显

process.env.VUE_APP_SERVE:这个是全局的,公司地址,比如https://xx.cn,如果图片显示不出来,可以问后端要不要拼接其他,可以在浏览器测试

以下这俩个方法,直接复制,把参数对好就能转为file,格式是[FILE]

imageToBase64:图片转base64

base64ToFile:base64转File

that.formInline.files:用于存储file格式图片

  query() {if (files.length > 0) {files.forEach((item) => {this.fileImgList.push({url: process.env.VUE_APP_SERVE + '/files' + item.path,name: item.originalname});var image = new Image();image.crossOrigin = '';image.src = process.env.VUE_APP_SERVE + '/files' + item.path; // 'https://xx.cn' + itemconst that = this;image.onload = function () {const base64 = that.imageToBase64(image); // 图片转base64const file = that.base64ToFile(base64, item.path); // base64转Filethat.formInline.files.push(file);};});}},imageToBase64(img) {var canvas = document.createElement('canvas');canvas.width = img.width;canvas.height = img.height;var ctx = canvas.getContext('2d');ctx.drawImage(img, 0, 0, img.width, img.height);var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();var dataURL = canvas.toDataURL('image/jpeg' + ext);return dataURL;},base64ToFile(urlData, fileName) {const arr = urlData.split(',');const mime = arr[0].match(/:(.*?);/)[1];const bytes = atob(arr[1]); // 解码base64let n = bytes.length;const ia = new Uint8Array(n);while (n--) {ia[n] = bytes.charCodeAt(n);}return new File([ia], fileName, { type: mime });}

 2.删除已上传图片

直接复制,这个是删除[FILE,FILE]的图片

 handleRemove(file) {// 从列表中删除当前的图片var that = this;try {var delname = file.url.split('/');that.formInline.files = that.formInline.files.filter((ele) => {var name = ele.name.split('/');return name[name.length - 1] !== delname[delname.length - 1];});console.log(that.formInline.files);} catch (error) {}}

3.上传图片

上传图片的change事件,每次上传成功把file.raw给files,注意!!file.raw就是后端需要的file格式的图片

    OnChange(file, fileList) {const isType = file.type === "image/jpeg" || "image/png";const isLt5M = file.size / 1024 / 1024 < 5;if (!isType) {this.$message.error("上传图片只能是 JPG 格式!");fileList.pop();}if (!isLt5M) {this.$message.error("上传图片大小不能超过 5MB!");fileList.pop();}this.formInline.files.push(file.raw);},

4.上传多张图片并且携带额外参数

注意!!这边如果要传数组,需要先转换为json格式再发给后端

        async setCompanySubmit() {let formData = new FormData(); //  用FormData存放上传文件this.formInline.files.forEach((file, index) => {formData.append('files', file);});let { name, tel, truename, id } = this.formInline;formData.append('name', name);formData.append('tel', tel);formData.append('truename', truename);formData.append('id', id);const res = await Api_setCompany(formData);if (res.code == 200) {this.$message.success('成功!!!');this.unitDialogVisible = false;this.fileImgList = [];this.$refs.uploadCompanyRef.clearFiles();}}

上传参数如下,有多个files文件 

5.完整代码(仅作参考,需要根据实际情况修改)

<template><div><el-uploadaction="#"list-type="picture-card"multiple:on-remove="handleRemove":on-change="OnChange":file-list="fileImgList":auto-upload="false"ref="uploadCompanyRef"><i class="el-icon-plus"></i><div class="el-upload__tip" slot="tip">只能上传jpg/png文件,最多上传5张且单张图片不超过5M</div></el-upload><el-button type="primary" size="default" @click="setCompanySubmit()">上传</el-button></div>
</template><script>
export default {data() {return {fileImgList: [],formInline: {files: [],name: '',id: 0}};},mounted() {this.query();},methods: {query() {if (files.length > 0) {files.forEach((item) => {this.fileImgList.push({url: process.env.VUE_APP_SERVE + '/files' + item.path,name: item.originalname});var image = new Image();image.crossOrigin = '';image.src = process.env.VUE_APP_SERVE + '/files' + item.path; // 'https://xx.cn' + itemconst that = this;image.onload = function () {const base64 = that.imageToBase64(image); // 图片转base64const file = that.base64ToFile(base64, item.path); // base64转Filethat.formInline.files.push(file);};});}},imageToBase64(img) {var canvas = document.createElement('canvas');canvas.width = img.width;canvas.height = img.height;var ctx = canvas.getContext('2d');ctx.drawImage(img, 0, 0, img.width, img.height);var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();var dataURL = canvas.toDataURL('image/jpeg' + ext);return dataURL;},base64ToFile(urlData, fileName) {const arr = urlData.split(',');const mime = arr[0].match(/:(.*?);/)[1];const bytes = atob(arr[1]); // 解码base64let n = bytes.length;const ia = new Uint8Array(n);while (n--) {ia[n] = bytes.charCodeAt(n);}return new File([ia], fileName, { type: mime });},handleRemove(file) {// 从列表中删除当前的图片var that = this;try {var delname = file.url.split('/');that.formInline.files = that.formInline.files.filter((ele) => {var name = ele.name.split('/');return name[name.length - 1] !== delname[delname.length - 1];});console.log(that.formInline.files);} catch (error) {}},OnChange(file, fileList) {console.log(file, fileList, '多选情况下传参');const isType = file.type === 'image/jpeg' || 'image/png';const isLt5M = file.size / 1024 / 1024 < 5;if (!isType) {this.$message.error('上传图片只能是 JPG 格式!');fileList.pop();}if (!isLt5M) {this.$message.error('上传图片大小不能超过 5MB!');fileList.pop();}this.formInline.files.push(file.raw);},async setCompanySubmit() {let formData = new FormData(); //  用FormData存放上传文件this.formInline.files.forEach((file, index) => {formData.append('files', file);});let { name, tel, truename, id } = this.formInline;formData.append('name', name);formData.append('tel', tel);formData.append('truename', truename);formData.append('id', id);const res = await Api_setCompany(formData);if (res.code == 200) {this.$message.success('成功!!!');this.unitDialogVisible = false;this.fileImgList = [];this.$refs.uploadCompanyRef.clearFiles();}}}
};
</script><style lang="scss" scoped></style>

 6.照片墙效果

文章到此结束,希望对你有所帮助~

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 在 Windows 上安装 PostgreSQL
  • 解决echarts在uniapp里tooltip,legend不能点击的问题
  • 项目实战--C#实现图书馆信息管理系统
  • WEB渗透信息收集篇--IP和端口信息
  • 【C语言】 约瑟夫环,循环链表实现
  • 一个定期自动更换特定账号的密码的脚本
  • Android、Java反编译工具JADX
  • CSI-RS在信道中传输的过程
  • 使用脚本搭建MySQL数据库基础环境
  • JavaScript函数学习笔记[Web开发]
  • ts -> class -> abstract
  • CID引流-拼多多案例
  • 前端系列-7 Vue3响应式数据
  • 【简历】吉林某一本大学:JAVA秋招简历指导,简历通过率比较低
  • maven archetype
  • 【附node操作实例】redis简明入门系列—字符串类型
  • GitUp, 你不可错过的秀外慧中的git工具
  • hadoop入门学习教程--DKHadoop完整安装步骤
  • js ES6 求数组的交集,并集,还有差集
  • Logstash 参考指南(目录)
  • Map集合、散列表、红黑树介绍
  • mysql 5.6 原生Online DDL解析
  • mysql中InnoDB引擎中页的概念
  • React16时代,该用什么姿势写 React ?
  • SQLServer之创建显式事务
  • 面试遇到的一些题
  • 判断客户端类型,Android,iOS,PC
  • 前端_面试
  • 如何在 Tornado 中实现 Middleware
  • 使用Swoole加速Laravel(正式环境中)
  • 一起来学SpringBoot | 第十篇:使用Spring Cache集成Redis
  • 你对linux中grep命令知道多少?
  • #NOIP 2014#Day.2 T3 解方程
  • #微信小程序(布局、渲染层基础知识)
  • (1)虚拟机的安装与使用,linux系统安装
  • (52)只出现一次的数字III
  • (C11) 泛型表达式
  • (web自动化测试+python)1
  • (二)十分简易快速 自己训练样本 opencv级联lbp分类器 车牌识别
  • (六)软件测试分工
  • (三)模仿学习-Action数据的模仿
  • (删)Java线程同步实现一:synchronzied和wait()/notify()
  • (十八)Flink CEP 详解
  • (学习日记)2024.03.12:UCOSIII第十四节:时基列表
  • (一)python发送HTTP 请求的两种方式(get和post )
  • (转)【Hibernate总结系列】使用举例
  • (总结)Linux下的暴力密码在线破解工具Hydra详解
  • .NET 使用 ILMerge 合并多个程序集,避免引入额外的依赖
  • .NET框架类在ASP.NET中的使用(2) ——QA
  • .net连接MySQL的方法
  • .Net通用分页类(存储过程分页版,可以选择页码的显示样式,且有中英选择)
  • .NET下的多线程编程—1-线程机制概述
  • .NET中两种OCR方式对比
  • .sdf和.msp文件读取
  • @converter 只能用mysql吗_python-MySQLConverter对象没有mysql-connector属性’...