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>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ant design vue 中上图片时,可以通过配置 token 和其他参数来实现。首先,在上组件中设置 action 属性为上图片的接口地址。然后,通过 headers 属性设置 token 参数,使其与图片一起发送到服务器。具体步骤如下: 1. 导入需要的组件:在组件中首先导入 Upload 组件和 message 组件,用于实现上图片和提示消息。 ```javascript import { Upload, message } from 'ant-design-vue'; ``` 2. 定义上图片的接口地址和要递的其他参数: ```javascript const uploadUrl = 'your_upload_api_url'; const token = 'your_token'; const otherParams = { param1: 'value1', param2: 'value2', }; ``` 3. 在模板中使用 Upload 组件,并配置上图片的相关属性: ```html <template> <div> <Upload action="{{uploadUrl}}" :headers="{ Authorization: token }" :data="otherParams" :on-success="handleUploadSuccess" :on-error="handleUploadError" > <button>选择文件</button> </Upload> </div> </template> ``` 4. 处理上成功和失败的回调函数: ```javascript methods: { handleUploadSuccess(response) { // 上成功后的逻辑处理 message.success('上成功'); }, handleUploadError(error) { // 上失败后的逻辑处理 message.error('上失败'); }, }, ``` 以上是使用 ant design vue 实现上带 token 和其他参数的图片的步骤。通过配置 action、headers 和 data 属性,即可将 token 和其他参数一起发送到服务器。在上成功和失败的回调函数中,可以添加相应的逻辑处理和提示消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值