【Vue】以RuoYi框架前端为例,ElementUI封装图片上传组件——将图片信息转成base64后提交到后端保存

news/2024/9/29 2:14:58/

RuoYi 框架本身对于图片上传功能,在ElementUI<el-upload> 组件的基础装封装了 @/components/ImageUpload/index.vue 组件。本组件就是在 RuoYi 自定义的 <ImageUpload> 组件的基础上进行改造,将图片的信息在上传之前处理成 base64 格式,用于提交到后端接口,以及前端图片相应的预览展示。

自定义组件 ImageUploadBase64

组件目录 : @/components/ImageUploadBase64/index.vue

<template><div class="component-upload-image"><el-upload ref="imageUploadRef"action="#"list-type="picture-card"accept=".png, .jpeg, .jpg":limit="limit":on-change="handleChange":on-remove="handleRemove":on-preview="handlePictureCardPreview":on-exceed="handleExceed":file-list="fileList":class="{hide: this.fileList.length >= this.limit}":show-file-list="true":auto-upload="false"><i class="el-icon-plus"></i></el-upload><el-dialog :visible.sync="previewDialogVisible" title="图片预览" width="800" append-to-body><el-image style="display: block; max-width: 100%; margin: 0 auto":src="previewDialogImageUrl" alt=""></el-image></el-dialog></div>
</template>
<script>export default {props: {// 对应父组件 v-model绑定,对应本组件 this.$emit("input",参数)绑定value: [String, Object, Array],// 图片数量限制limit: {type: Number,default: 5,},// 大小限制(MB)fileSize: {type: Number,default: 5,},// 文件类型, 例如['png', 'jpg', 'jpeg']fileType: {type: Array,default: () => ["png", "jpg", "jpeg"],},},data() {return {// 图片预览弹窗 显隐previewDialogVisible: false,// 图片预览 urlpreviewDialogImageUrl: '',// 待上传的图片集合 是转化完base64 后的结果fileList: [/*{name:'',url:''}*/]}},watch: {value: {handler(val) {if (val) {// 首先将值转为数组const list = Array.isArray(val) ? val : this.value.split(',');// 然后将数组转为对象数组this.fileList = list.map(item => {if (typeof item === "string") {item = {name: item, url: item};}return item;});} else {this.fileList = [];return [];}},deep: true,immediate: true}},methods: {/*** 校验文件尺寸是否符合要求 和类型是否是图片* @param file* @returns {boolean}*/handleFileValidate(file) {// 上传文件的类型let type = file.raw.type || file.type;let isImg = type.indexOf("image") > -1;if (isImg) {if (this.fileSize) {const isLt = file.size / 1024 / 1024 < this.fileSize;if (!isLt) {this.$message.error(`上传头像图片大小不能超过 ${this.fileSize} MB!`);return false;} else {return true;}}} else {this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);// 不是图片格式return false;}},/* 添加文件、上传成功和上传失败时都会被调用 */handleChange(file, fileList) {if (this.handleFileValidate(file)) {this.fileToBase64(file);} else {// 删除尺寸大的图片 或者非图片类型的文件let lastIndex = fileList.length - 1;if (lastIndex > -1) {fileList.splice(lastIndex, 1);}}},/*** 删除图片* @param file 被删除的图片* @param fileList 剩余的文件信息列表*/handleRemove(file, fileList) {const findex = this.fileList.map(f => f.url).indexOf(file.url);if (findex > -1) {// 删除对应的 文件数据this.fileList.splice(findex, 1);this.$emit("input", this.listToArray(this.fileList));}},/*预览图片*/handlePictureCardPreview(file) {this.previewDialogImageUrl = file.url;this.previewDialogVisible = true;},/*** 文件个数超出* @param files 超出的文件信息* @param fileList 原来已经添加的文件信息*/handleExceed(files, fileList) {this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);},/*** 将el-upload组件上传的文件转为base64* @param file*/fileToBase64(file) {var reader = new FileReader();reader.readAsDataURL(file.raw); // 转换为Base64reader.onload = e => {// 当转换完成后,e.target.result就是Base64字符串const base64 = e.target.result;this.fileList.push({name: base64, url: base64});this.$emit("input", this.listToArray(this.fileList));};},// list中的元素{name:'',url:''} 转 url字符串listToArray(list) {let arr = [];for (let i in list) {arr.push(list[i].url);}return arr;}}
}</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {display: none;
}// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {transition: all 0s;
}::v-deep .el-list-enter, .el-list-leave-active {opacity: 0;transform: translateY(0);
}
</style>

表单中引用如下

<template><div class="app-container"><!-- 添加或修改对话框 --><el-dialog :title="title" :visible.sync="open" width="500px" append-to-body><el-form ref="form" :model="form" :rules="rules" :show-message="false" label-width="80px"><el-col :span="24"><el-form-item label="上传图片"><ImageUploadBase64 v-model="form.base64DataList" :file-size="10" @input="handleImageInput"></ImageUploadBase64></el-form-item></el-col></el-row></el-form><div slot="footer" class="dialog-footer"><el-button type="primary" @click="submitForm()">保 存</el-button><el-button @click="cancel">取 消</el-button></div></el-dialog></div>
</template><script>
import ImageUploadBase64 from "@/components/ImageUploadBase64/index.vue";import {listWorkInfo, getWorkInfo, delWorkInfo, addWorkInfo, updateWorkInfo} from "@/api/basic/work";export default {name: "Work",components: {ImageUploadBase64},data() {return {// 弹出层标题title: "",// 是否显示弹出层open: false,// 表单参数form: {},};},created() {this.getList();},methods: {/*** 子组件 this.$emit("input", this.listToArray(this.fileList)); 返回的数据* @param fileList*/handleImageInput(fileList){// 这里返回的就是base64字符串的数组,可以直接提交后端接口,也可以根据业务做其他处理console.log("handleImageInput-----:", fileList)},// 取消按钮cancel() {this.open = false;this.reset();},// 表单重置reset() {this.form = {id: nullbase64DataList:[]};this.resetForm("form");},/** 新增按钮操作 */handleAdd() {this.reset();this.title = "添加工作信息";this.open = true;},/** 修改按钮操作 */handleUpdate(row) {this.reset();const id = row.id || this.idsgetWorkInfo(id).then(response => {this.form = response.data;this.open = true;this.title = "修改工作信息";});},/** 提交按钮 */submitForm: function () {this.$refs["form"].validate(valid => {if (valid) {if (this.form.id != undefined) {updateWorkInfo(this.form).then(response => {this.$modal.msgSuccess("修改成功");this.open = false;this.getList();});} else {addWorkInfo(this.form).then(response => {this.$modal.msgSuccess("新增成功");this.open = false;this.getList();});}}});}}
};
</script>

这个组件将图片信息直接在前端转化成 base64格式的字符串数字,后端可以直接使用List<String> 接收图片的信息并进行后续的处理。


http://www.ppmy.cn/news/1531219.html

相关文章

如何选择高品质SD卡

如何选择高品质SD卡 SD卡&#xff08;Secure Digital Memory Card&#xff09;是一种广泛使用的存储器件&#xff0c;因其快速的数据传输速度、可热插拔的特性以及较大的存储容量&#xff0c;广泛应用于各种场景&#xff0c;例如在便携式设备如智能手机、平板电脑、运动相机等…

Xcode 16 Pod init 报错

pod init failed in Xcode 16 Issue #12583 CocoaPods/CocoaPods GitHub 根据你提供的步骤&#xff0c;以下是详细的操作指南来解决 CocoaPods 的问题&#xff1a; ### 步骤 1&#xff1a;在 Xcode 中转换项目文件夹为组 1. 打开你的 Xcode 项目。 2. 在左侧的项目导航器…

YOLOv8 Flask整合问题

YOLOv8 Flask整合问题 yolov8 flask 后代码没有进行推理问题。 Bug model.predict()pyinstallerHTTPServer/flask: not executing yolov8是异步线程调用了&#xff0c;flask打包exe后会应该异步问题&#xff0c;model.predict()不会进行返回&#xff0c;导致没有看着没有执行而…

Elasticsearch黑窗口启动乱码问题解决方案

问题描述 elasticsearch启动后有乱码现象 解决方案&#xff1a; 提示&#xff1a;这里填写该问题的具体解决方案&#xff1a; 到 \config 文件下找到 jvm.options 文件 打开后 在文件末尾空白处 添加 -Dfile.encodingGBK 保存后重启即可。

松山湖全球首秀:传祺华为概念车发布

9月24日晚&#xff0c;传祺与华为联合举办的创「新」计划成果分享会暨全新概念车品鉴会&#xff0c;在华为东莞松山湖基地圆满落幕。 作为本次活动的焦点&#xff0c;传祺与华为双方联手打造的首款概念车「1 Concept」&#xff0c;也在会场正式登场亮相&#xff0c;这也标志着传…

美国林氏集团宣布全面进军Web3领域

吉隆坡&#xff0c;马来西亚——近日举行的第六界博览会上&#xff0c;美国林氏集团董事局主席林建中先生宣布&#xff0c;集团将通过旗下的大东亚银行创建一个全新的、合规的区块链交易所&#xff0c;并正式进军Web3、元宇宙及AI领域。同时&#xff0c;美国林氏集团将利用其在…

Linux基础4-进程2(Linux中的进程状态,R,S,D,T,t,Z,X,僵尸进程,孤儿进程)

上篇文章&#xff1a;Linux基础4-进程1&#xff08;操作系统&#xff0c;进程介绍&#xff0c;Linux进程相关命令&#xff0c;getpid&#xff0c;fork&#xff09;-CSDN博客 本章重点&#xff1a; 进程状态相关知识 目录 1. 进程常见的状态 2.普遍的操作系统理解进程状态 3.…

Qemu开发ARM篇-5、buildroot制作根文件系统并挂载启动

文章目录 1、 buildroot源码获取2、buildroot配置3、buildroot编译4、挂载根文件系统 在上一篇 Qemu开发ARM篇-4、kernel交叉编译运行演示中&#xff0c;我们编译了kernel&#xff0c;并在qemu上进行了运行&#xff0c;但到最后&#xff0c;在挂载根文件系统时候&#xff0c;挂…