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

news2024/9/20 6:13:57

需求: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' + item
                    const that = this;
                    image.onload = function () {
                        const base64 = that.imageToBase64(image); // 图片转base64
                        const file = that.base64ToFile(base64, item.path); // base64转File
                        that.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]); // 解码base64
            let 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-upload
            action="#"
            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' + item
                    const that = this;
                    image.onload = function () {
                        const base64 = that.imageToBase64(image); // 图片转base64
                        const file = that.base64ToFile(base64, item.path); // base64转File
                        that.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]); // 解码base64
            let 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.照片墙效果

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1944140.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Java之数组应用-选择排序-插入排序

已经完全掌握了冒泡排序和二分查找的同学&#xff0c;可以自己尝试学习选择、插入排序。不要求今天全部掌握&#xff0c;最近2-3天掌握即可&#xff01; 1 选择排序 选择排序(Selection Sort)的原理有点类似插入排序&#xff0c;也分已排序区间和未排序区间。但是选择排序每次…

《峡谷小狐仙-多模态角色扮演游戏助手》复现流程

YongXie66/Honor-of-Kings_RolePlay: The Role Playing Project of Honor-of-Kings Based on LnternLM2。峡谷小狐仙--王者荣耀领域的角色扮演聊天机器人&#xff0c;结合多模态技术将英雄妲己的形象带入大模型中。 (github.com) https://github.com/chg0901/Honor_of_Kings…

盘点2024年大家都在使用的AI智能写作工具

在科技发达的现在社会&#xff0c;AI已经悄悄的渗入我们生活的各种角落。不知道你有没有尝试过用ai智能写作来完成一些文章创作呢&#xff1f;这次我介绍几个可以提升效率的ai智能写作工具给你试试吧。 1.笔&#xff5c;灵AI写作 CSDN 传送门&#xff1a;https://ibiling.cn…

Interesting bug caused by getattr

题意&#xff1a;由 getattr 引起的有趣的 bug 问题背景&#xff1a; I try to train 8 CNN models with the same structures simultaneously. After training a model on a batch, I need to synchronize the weights of the feature extraction layers in other 7 models. …

Vue3+Element Plus 实现table表格中input的验证

实现效果 html部分 <template><div class"table"><el-form ref"tableFormRef" :model"form"><el-table :data"form.detailList"><el-table-column type"selection" width"55" align&…

初识c++(string和模拟实现string)

一、标准库中的string类 string类的文档介绍&#xff1a;cplusplus.com/reference/string/string/?kwstring 1、auto和范围for auto&#xff1a; 在早期C/C中auto的含义是&#xff1a;使用auto修饰的变量&#xff0c;是具有自动存储器的局部变量&#xff0c;后来这个 不重…

【北航主办丨本届SPIE独立出版丨已确认ISSN号】第三届智能机械与人机交互技术学术会议(IHCIT 2024,7月27)

由北京航空航天大学指导&#xff0c;北京航空航天大学自动化科学与电气工程学院主办&#xff0c;AEIC学术交流中心承办的第三届智能机械与人机交互技术学术会议&#xff08;IHCIT 2024&#xff09;将定于2024年7月27日于中国杭州召开。 大会面向基础与前沿、学科与产业&#xf…

初识c++:string类 (1)

目录 # 初识c&#xff1a;string类 1.为什么学习string类 2.标准库中的string类 2.1 string类的了解 2.2 auto和范围for 2.3 string类的常用接口说明 2.3.1string类对象的常见构造 2.3.2string类对象的容量操作 2.3.3string类对象的访问及遍历操作 2.3.4string类对象…

DNS概述及DNS服务器的搭建(twelve day)

回顾 关闭防火墙 systemctl stop firewalld 永久停止防火墙 systemctl disable firewalld 关闭selinux setenforce 0 永久关闭selinux安全架构 vim /etc/selinux/config 修改静态IP地址 vim /etc/sysconfig/network-scripts/ifcfg-ens160 #修改uuid的目的是为了保证网络的唯一…

计算机的错误计算(四十)

摘要 计算机的错误计算&#xff08;三十九&#xff09;阐明有时计算机将0算成非0&#xff0c;非0算成0&#xff1b;并且前面介绍的这些错误计算相对来说均是由软件完成。本节讨论手持式计算器对这些算式的计算效果。 例1. 用手持式计算器计算 与 . 我们用同一个计算器计算…

机械学习—零基础学习日志(高数10——函数图形)

零基础为了学人工智能&#xff0c;真的开始复习高数 函数图像&#xff0c;开始新的学习&#xff01;本次就多做一做题目&#xff01; 第一题&#xff1a; 这个解法是有点不太懂的了。以后再多研究一下。再出一道题目。 张宇老师&#xff0c;比较多提示了大家&#xff0c;一定…

哪些工作可以年入几十万到2亿?

关注卢松松&#xff0c;会经常给你分享一些我的经验和观点。 从今年起&#xff0c; 每个月都会有年入几十万到2亿的新闻案例出来&#xff0c;而且很多都是官方媒体发的&#xff0c;你们看看&#xff1a; 7月19日35岁小伙扛楼一年多存了40万 7月4日老板娘一天卖出200斤知了日入…

Leetcode3217. 从链表中移除在数组中存在的节点

Every day a Leetcode 题目来源&#xff1a;3217. 从链表中移除在数组中存在的节点 解法1&#xff1a;集合 链表遍历 代码&#xff1a; /** lc appleetcode.cn id3217 langcpp** [3217] 从链表中移除在数组中存在的节点*/// lc codestart /*** Definition for singly-link…

docker--容器数据进行持久化存储的三种方式

文章目录 为什么Docker容器需要使用持久化存储1.什么是Docker容器&#xff1f;2.什么是持久化存储&#xff1f;3.为什么Docker容器需要持久化存储&#xff1f;4.Docker如何实现持久化存储&#xff1f;(1)、Docker卷(Volumes)简介适用环境:使用场景:使用案例: (2)、绑定挂载&…

Python 实现PDF和TIFF图像之间的相互转换

PDF是数据文档管理领域常用格式之一&#xff0c;主要用于存储和共享包含文本、图像、表格、链接等的复杂文档。而TIFF&#xff08;Tagged Image File Format&#xff09;常见于图像处理领域&#xff0c;主要用于高质量的图像文件存储。 在实际应用中&#xff0c;我们可能有时需…

哪个邮箱最安全最好用啊

企业邮箱安全至关重要&#xff0c;需保护隐私、防财务损失、维护通信安全、避免纠纷&#xff0c;并维持业务连续性。哪个企业邮箱最安全好用呢&#xff1f;Zoho企业邮箱&#xff0c;采用加密技术、反垃圾邮件和病毒保护&#xff0c;支持多因素认证&#xff0c;确保数据安全合规…

php的文件上传

&#x1f3bc;个人主页&#xff1a;金灰 &#x1f60e;作者简介:一名简单的大一学生;易编橙终身成长社群的嘉宾.✨ 专注网络空间安全服务,期待与您的交流分享~ 感谢您的点赞、关注、评论、收藏、是对我最大的认可和支持&#xff01;❤️ &#x1f34a;易编橙终身成长社群&#…

【每日刷题Day85】

【每日刷题Day85】 &#x1f955;个人主页&#xff1a;开敲&#x1f349; &#x1f525;所属专栏&#xff1a;每日刷题&#x1f34d; &#x1f33c;文章目录&#x1f33c; 1. 125. 验证回文串 - 力扣&#xff08;LeetCode&#xff09; 2. 43. 字符串相乘 - 力扣&#xff08;L…

【es】elasticsearch 自定义排序-按关键字位置排序

一 背景 要求es查询的结果按关键字位置排序&#xff0c;位置越靠前优先级越高。 es版本7.14.0&#xff0c;项目是thrift&#xff0c;也可以平替springboot&#xff0c;使用easyes连接es。 二 easyes使用 配easyes按官方文档就差不多了 排序 | Easy-Es 主要的一个问题是easy…

FPGA深入浅出IP核学习(一)-- vivado中clk IP MMCM核的使用

FPGA深入浅出IP核学习系列文章主要是自己关于学习FGPA IP核的学习笔记&#xff0c;供大家参考学习指正。 目录 前言 一、MMCM-IP核简介 二、MMCM-IP核使用 1.IP核配置 2.模块程序设计 总结 前言 本文主要参考B站野火FGPA相关学习视频、正点原子达芬奇FPGA开发指南和赛灵思官方用…