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

打印 上一主题 下一主题

主题 878|帖子 878|积分 2634

实现结果:

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

1.在项目components/base下新建UploadNew.vue文件(上传图片公共组件)
  1. <template>
  2.   <div class="clearfix">
  3.     <a-upload
  4.       v-model:file-list="fileList"
  5.       action="/platform-gateway/platform-file/security/chain"
  6.       list-type="picture-card"
  7.        :headers="headers"
  8.       @preview="handlePreview"
  9.       @change="handleChange"
  10.     >
  11.       <div v-if="fileList.length < props.limit">
  12.         <plus-outlined />
  13.         <div style="margin-top: 8px">上传</div>
  14.       </div>
  15.     </a-upload>
  16.     <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
  17.       <img alt="example" style="width: 100%" :src="previewImage" />
  18.     </a-modal>
  19.   </div>
  20. </template>
  21. <script lang="ts" setup>
  22. import { PlusOutlined } from '@ant-design/icons-vue';
  23. import { ref } from 'vue';
  24. import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
  25. import { HttpClientUtils } from '../../configure/http/httpClientUtils'
  26. interface Props {
  27.   accept: string, // 上传文件的格式,
  28.   limit: number,//上传图片数量
  29.   fileListJson :UploadProps['fileList']
  30. }
  31. const props = defineProps<Props>()
  32. function getBase64(file: File) {
  33.   return new Promise((resolve, reject) => {
  34.     const reader = new FileReader();
  35.     reader.readAsDataURL(file);
  36.     reader.onload = () => resolve(reader.result);
  37.     reader.onerror = error => reject(error);
  38.   });
  39. }
  40. const previewVisible = ref(false);
  41. const previewImage = ref('');
  42. const previewTitle = ref('');
  43. //调用后端接口请求头
  44. const headers = {
  45.     authorization: HttpClientUtils.getToken(),
  46.     platform: 'WEB',
  47.     serviceCode: 'athletics-service'
  48. }
  49. const $emit = defineEmits(["uploadDone"])
  50. const fileList = ref<UploadProps['fileList']>([
  51. ]);
  52. if (props.fileListJson) {
  53.     fileList.value = props.fileListJson
  54. }
  55. const handleCancel = () => {
  56.   previewVisible.value = false;
  57.   previewTitle.value = '';
  58. };
  59. const handlePreview = async (file: UploadProps['fileList'][number]) => {
  60.   if (!file.url && !file.preview) {
  61.     file.preview = (await getBase64(file.originFileObj)) as string;
  62.   }
  63.   previewImage.value = file.url || file.preview;
  64.   previewVisible.value = true;
  65.   previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
  66. };
  67. const handleChange = (info: UploadChangeParam) => {
  68.   if (info.file.status === 'done') {
  69.     //   imageId.value = 'http://192.168.5.13/platform-gateway/platform-file/security/chain?fileName=' + info.file.response.data[0] + '&serviceCode=athletics-service'
  70.       $emit("uploadDone", info.fileList)
  71.   }
  72. };
  73. </script>
  74. <style scoped>
  75. /* you can make up upload button and sample style by using stylesheets */
  76. .ant-upload-select-picture-card i {
  77.   font-size: 32px;
  78.   color: #999;
  79. }
  80. .ant-upload-select-picture-card .ant-upload-text {
  81.   margin-top: 8px;
  82.   color: #666;
  83. }
  84. </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']>([]);//轮播图
  1. const formData = reactive({
  2.   venue: {
  3.     headerUrl:props.data?.headerUrl,
  4.     bannerUrl:props.data?.bannerUrl,
  5.   },
  6. })
复制代码
2.1 表单样式、使用组件
  1.   <a-form-item :name="['venue', 'headerUrl']" label="封面图" :rules="[{ required: true }]">
  2.       <AntdUploadFile
  3.       :fileListJson="fileListJson"
  4.       :limit="1"
  5.       accept=""
  6.       type="frontIdcard"
  7.       @upload-load="onUploading"
  8.       @upload-done="onUploadDone"
  9.       >
  10.       </AntdUploadFile>
  11.     </a-form-item>
  12.     <a-form-item :name="['venue', 'bannerUrl']" label="场馆轮播" :rules="[{ required: true }]">
  13.     <AntdUploadFile
  14.       :limit="4"
  15.       accept=""
  16.       :fileListJson="fileListJson1"
  17.       type="frontIdcard1"
  18.       @upload-load="onUploading1"
  19.       @upload-done="onUploadDone1"
  20.       >
  21.       </AntdUploadFile>
  22.     </a-form-item>
复制代码
2.2 上传图片成功 ,点保存后传给后端
  1. // 封面图片上传成功(单个图)
  2. const onUploadDone = (fileList: any) => {
  3.   // 文件上传成功后返回的文件信息 type,是为了一个页面引用多少文件上传作的区分
  4.   if (fileList.length) {
  5.         formData.venue.headerUrl= fileList[0].response.data
  6.   
  7.   }
  8.   console.log( formData.venue.headerUrl,"上传成功后的参数 ", fileList);
  9. }
  10. // 轮播图片上传成功(多张图)
  11. const onUploadDone1 = (fileList: any) => {
  12.   // 文件上传成功后返回的文件信息 type,是为了一个页面引用多少文件上传作的区分
  13.   let bannerUrl = []
  14.   if (fileList.length) {
  15.     for (let i = 0; i < fileList.length; i++) {
  16.       if (fileList[i].response) {
  17.                bannerUrl.push({
  18.                "url":fileList[i].response.data,
  19.               })
  20.       } else {
  21.      //将fileName= 后面的数据和&前的数据截取push到url后,转为json字符串传给后端
  22.         const index = fileList[i].url.indexOf('fileName=')
  23.         let newIndex: any
  24.         if (index !== -1) {
  25.           const start = fileList[i].url.slice(index + 'fileName='.length)
  26.           const endIndex = start.indexOf('&')
  27.           if (endIndex !== -1) {
  28.             newIndex = start.slice(0,endIndex)
  29.           }
  30.         }
  31.           bannerUrl.push({
  32.             "url": newIndex,
  33.            })
  34.          }     
  35.        }
  36.   }
  37.   formData.venue.bannerUrl =JSON.stringify(bannerUrl)
  38. }
复制代码
2.3 点编辑时回显(因本接口后端返回的数据需要拼接,可根据自行情况修改)
  1. if (props.data.bannerUrl||props.data.headerUrl) {
  2.               fileListJson.value.push({
  3.                "url":'http://platform-file/security/chain?fileName=' + props.data.headerUrl + '&serviceCode=athletics-service',
  4.               })
  5.   const bannerList =  JSON.parse(props.data.bannerUrl)//json字符串转为数组
  6.   console.log(bannerList,'里面有这个图片吗')
  7.             for (let i = 0;i< bannerList.length;i++) {
  8.               fileListJson1.value.push({
  9.                "url":'后端返回的地址',
  10.               })
  11.   }
  12. }
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

美丽的神话

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表