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

vue3中antd上传图片组件及回显

实现效果:

调用后端接口后,后端返回的数据:

1.在项目components/base下新建UploadNew.vue文件(上传图片公共组件)

<template><div class="clearfix"><a-uploadv-model:file-list="fileList"action="/platform-gateway/platform-file/security/chain"list-type="picture-card":headers="headers"@preview="handlePreview"@change="handleChange" ><div v-if="fileList.length < props.limit"><plus-outlined /><div style="margin-top: 8px">上传</div></div></a-upload><a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel"><img alt="example" style="width: 100%" :src="previewImage" /></a-modal></div>
</template>
<script lang="ts" setup>
import { PlusOutlined } from '@ant-design/icons-vue';
import { ref } from 'vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import { HttpClientUtils } from '../../configure/http/httpClientUtils'interface Props {accept: string, // 上传文件的格式,limit: number,//上传图片数量fileListJson :UploadProps['fileList']
}
const props = defineProps<Props>()
function getBase64(file: File) {return new Promise((resolve, reject) => {const reader = new FileReader();reader.readAsDataURL(file);reader.onload = () => resolve(reader.result);reader.onerror = error => reject(error);});
}const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
//调用后端接口请求头
const headers = {authorization: HttpClientUtils.getToken(),platform: 'WEB',serviceCode: 'athletics-service'
}
const $emit = defineEmits(["uploadDone"]) 
const fileList = ref<UploadProps['fileList']>([]);
if (props.fileListJson) {fileList.value = props.fileListJson
}
const handleCancel = () => {previewVisible.value = false;previewTitle.value = '';
};const handlePreview = async (file: UploadProps['fileList'][number]) => {if (!file.url && !file.preview) {file.preview = (await getBase64(file.originFileObj)) as string;}previewImage.value = file.url || file.preview;previewVisible.value = true;previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};const handleChange = (info: UploadChangeParam) => {if (info.file.status === 'done') {//   imageId.value = 'http://192.168.5.13/platform-gateway/platform-file/security/chain?fileName=' + info.file.response.data[0] + '&serviceCode=athletics-service'$emit("uploadDone", info.fileList)}
};
</script><style scoped>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {font-size: 32px;color: #999;
}.ant-upload-select-picture-card .ant-upload-text {margin-top: 8px;color: #666;
}
</style>

2.页面中使用

先引入:import AntdUploadFile  from "@/components/base/UploadNew.vue";

定义:

const props = defineProps({

  data: {} as any,

})//点编辑时父组件传入的回显数据

const fileListJson = ref<UploadProps['fileList']>([]);//封面

const fileListJson1 = ref<UploadProps['fileList']>([]);//轮播图

const formData = reactive({venue: {headerUrl:props.data?.headerUrl,bannerUrl:props.data?.bannerUrl,},
})

2.1 表单样式、使用组件

  <a-form-item :name="['venue', 'headerUrl']" label="封面图" :rules="[{ required: true }]"><AntdUploadFile:fileListJson="fileListJson":limit="1" accept="" type="frontIdcard" @upload-load="onUploading"@upload-done="onUploadDone" ></AntdUploadFile></a-form-item><a-form-item :name="['venue', 'bannerUrl']" label="场馆轮播" :rules="[{ required: true }]"><AntdUploadFile:limit="4" accept="" :fileListJson="fileListJson1"type="frontIdcard1" @upload-load="onUploading1"@upload-done="onUploadDone1" ></AntdUploadFile></a-form-item>

2.2 上传图片成功 ,点保存后传给后端

// 封面图片上传成功(单个图)
const onUploadDone = (fileList: any) => {// 文件上传成功后返回的文件信息 type,是为了一个页面引用多少文件上传作的区分if (fileList.length) {formData.venue.headerUrl= fileList[0].response.data}console.log( formData.venue.headerUrl,"上传成功后的参数 ", fileList);
}
// 轮播图片上传成功(多张图)
const onUploadDone1 = (fileList: any) => {// 文件上传成功后返回的文件信息 type,是为了一个页面引用多少文件上传作的区分let bannerUrl = []if (fileList.length) {for (let i = 0; i < fileList.length; i++) {if (fileList[i].response) {bannerUrl.push({"url":fileList[i].response.data,})} else {//将fileName= 后面的数据和&前的数据截取push到url后,转为json字符串传给后端const index = fileList[i].url.indexOf('fileName=')let newIndex: anyif (index !== -1) {const start = fileList[i].url.slice(index + 'fileName='.length)const endIndex = start.indexOf('&')if (endIndex !== -1) {newIndex = start.slice(0,endIndex)}}bannerUrl.push({"url": newIndex,})}     }}formData.venue.bannerUrl =JSON.stringify(bannerUrl) 
}

2.3 点编辑时回显(因本接口后端返回的数据需要拼接,可根据自行情况修改)

if (props.data.bannerUrl||props.data.headerUrl) {fileListJson.value.push({"url":'http://platform-file/security/chain?fileName=' + props.data.headerUrl + '&serviceCode=athletics-service',})const bannerList =  JSON.parse(props.data.bannerUrl)//json字符串转为数组console.log(bannerList,'里面有这个图片吗')for (let i = 0;i< bannerList.length;i++) {fileListJson1.value.push({"url":'后端返回的地址',})}}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • Android OkHttp3中HttpLoggingInterceptor使用
  • CV10_模型、特征图、CAM热力图可视化
  • 玩转springboot之SpringApplicationRunListener
  • 能够支持百度独立导航的智能手表你见过吗?
  • 【学习笔记】无人机(UAV)在3GPP系统中的增强支持(一)-3GPP TR 22.829 V17.1.0技术报告
  • Rust编程-I/O
  • 算法刷题笔记 合并集合(C++实现)
  • TensorBoard ,PIL 和 OpenCV 在深度学习中的应用
  • python--实验 11 模块
  • Qt+ESP32+SQLite 智能大棚
  • 6-5,web3浏览器链接区块链(react+区块链实战)
  • OpenCV解决验证码(数字和字母)识别(Python)
  • 了解redis
  • YOLOv5和LPRNet的车牌识别系统
  • Java二十三种设计模式-单例模式(1/23)
  • 8年软件测试工程师感悟——写给还在迷茫中的朋友
  • CentOS学习笔记 - 12. Nginx搭建Centos7.5远程repo
  • classpath对获取配置文件的影响
  • JavaScript异步流程控制的前世今生
  • JS学习笔记——闭包
  • Laravel 菜鸟晋级之路
  • Linux编程学习笔记 | Linux IO学习[1] - 文件IO
  • pdf文件如何在线转换为jpg图片
  • React-redux的原理以及使用
  • React系列之 Redux 架构模式
  • SOFAMosn配置模型
  • underscore源码剖析之整体架构
  • Vue 动态创建 component
  • 对超线程几个不同角度的解释
  • 关于Java中分层中遇到的一些问题
  • 记录一下第一次使用npm
  • 买一台 iPhone X,还是创建一家未来的独角兽?
  • 驱动程序原理
  • 设计模式走一遍---观察者模式
  • 深入浅出Node.js
  • 探索 JS 中的模块化
  • 微信端页面使用-webkit-box和绝对定位时,元素上移的问题
  • 微信小程序上拉加载:onReachBottom详解+设置触发距离
  • 我与Jetbrains的这些年
  • ​【数据结构与算法】冒泡排序:简单易懂的排序算法解析
  • ​云纳万物 · 数皆有言|2021 七牛云战略发布会启幕,邀您赴约
  • # Redis 入门到精通(一)数据类型(4)
  • #systemverilog# 之 event region 和 timeslot 仿真调度(十)高层次视角看仿真调度事件的发生
  • #进阶:轻量级ORM框架Dapper的使用教程与原理详解
  • #数学建模# 线性规划问题的Matlab求解
  • (01)ORB-SLAM2源码无死角解析-(56) 闭环线程→计算Sim3:理论推导(1)求解s,t
  • (4)logging(日志模块)
  • (C语言)输入一个序列,判断是否为奇偶交叉数
  • (Matlab)遗传算法优化的BP神经网络实现回归预测
  • (MonoGame从入门到放弃-1) MonoGame环境搭建
  • (Note)C++中的继承方式
  • (web自动化测试+python)1
  • (附源码)ssm基于微信小程序的疫苗管理系统 毕业设计 092354
  • (六)Flink 窗口计算
  • (论文阅读31/100)Stacked hourglass networks for human pose estimation