Ant Design Vue的上传图片组件Upload封装和遇到的问题

问题:上传图片后图片会打印两次的问题(因为什么引起的--也是看了文档找了一圈 主要是因为没有传uid这个参数 )

const handleUploadSuccess = (file) => {
    let list = cloneDeep(props.fileList);
    const imgData = { ...file, url: file.address, name: file.originalFileName, 
       uid: generateUid() }; // 这边绑定uid就好了 
    list.push(imgData);
    updateFileList(list);
  };

需求--封装Upload组件(这是我封装的 大家看看就好)

<template>
  <div class="clearfix">
    <Upload
      :file-list="fileList"
      list-type="picture-card"
      :customRequest="customRequest"
      @preview="handlePreview"
      :multiple="multiple"
      :showUploadList="showUploadList"
      :headers="headers"
      :disabled="disabled"
      :accept="accept"
      @change="handleUploadChange"
    >
      <!--       @remove="handleRemove" -->
      <div v-if="fileList.length < limit">
        <plus-outlined />
        <!-- <div style="margin-top: 8px">Upload</div> -->
      </div>
    </Upload>
    <Modal
      :open="previewVisible"
      title=""
      width="1000px"
      style="top: 20px"
      :footer="null"
      @cancel="handleCancel"
    >
      <img alt="example" style="width: 100%" :src="previewImage" />
    </Modal>
  </div>
</template>

<script setup lang="ts">
  import { uploadFileApi } from '@/api/corrosionInvestigate/index';
  import { getToken } from '@/utils/auth/index';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { message, Modal, Upload } from 'ant-design-vue';
  import { cloneDeep } from 'lodash-es';
  import { ref } from 'vue';
  const props = defineProps({
    limit: {
      type: Number,
      default: 9,
    },
    multiple: {
      type: Boolean,
      default: true, // 多选
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    showUploadList: {
      type: Boolean,
      default: true,
    },
    fileList: {
      type: Array,
      default: () => [],
    },
  });
  const emits = defineEmits(['update:fileList']);
  const accept = '.jpeg,.jpg,.png';
  const headers = { Authorization: getToken() };
  const customRequest = async (uploadFile) => {
    let formData = new FormData();
    formData.append('file', uploadFile.file);
    try {
      const res = await uploadFileApi(formData);
      if (res) {
        const file = res.data;
        // console.log(file, '成功地址');
        handleUploadSuccess(file);
      } else {
        message.error(`返回文件信息错误,联系管理员!`);
      }
    } catch (error) {
      console.log(error);
    }
  };
  const updateFileList = (array) => {
    emits('update:fileList', array);
  };
  const generateUid = () => {
    const uuid = Math.random().toString(24).substring(2, 12);
    return uuid;
  };
  const handleUploadSuccess = (file) => {
    let list = cloneDeep(props.fileList);
    const imgData = { ...file, url: file.address, name: file.originalFileName, uid: generateUid() };
    list.push(imgData);
    updateFileList(list);
  };
  const filterFileList = (file) => {
    let list = cloneDeep(props.fileList);
    list = list.filter((i: any) => i.uid !== file.uid);
    updateFileList(list);
  };
  const handleUploadError = (file) => {
    message.error(`${file.name} 上传失败`);
    filterFileList(file);
  };
  const handleRemove = (file) => {
    filterFileList(file);
  };
  const handleUploadChange = ({ file, fileList: list }) => {
    switch (file.status) {
      case 'removed':
        handleRemove(file);
        break;
      case 'done':
        handleUploadSuccess(file);
        break;
      case 'error':
        handleUploadError(file);
        break;
      default:
        console.log(file, 'change');
    }
    /* 
    // 2. read from response and show file link
      resFileList = resFileList.map(file => {
        if (file.response) {
          // Component will show file.url as link
          file.url = file.response.url;
        }
        return file;
      });
    */
  };
  function getBase64(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 handleCancel = () => {
    previewVisible.value = false;
    previewTitle.value = '';
  };
  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
    previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
  };
</script>
<style scoped lang="scss">
  /* you can make up upload button and sample style by using stylesheets */
  .ant-upload-select-picture-card i {
    color: #999;
    font-size: 32px;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>

相关推荐

  1. github代码遇到问题

    2024-04-25 18:00:04       60 阅读
  2. element-ui图片组件封装

    2024-04-25 18:00:04       40 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-25 18:00:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-25 18:00:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-25 18:00:04       82 阅读
  4. Python语言-面向对象

    2024-04-25 18:00:04       91 阅读

热门阅读

  1. Springboot的@Cacheable注解

    2024-04-25 18:00:04       32 阅读
  2. Android AIDL传递类对象

    2024-04-25 18:00:04       28 阅读
  3. pthread_cond_t和 sem_t的应用

    2024-04-25 18:00:04       27 阅读
  4. 数据库的END

    2024-04-25 18:00:04       26 阅读
  5. 基于享元模式实现连接池

    2024-04-25 18:00:04       35 阅读