ant-design-vue文件上传:Upload组件

上传是将信息(网页、文字、图片、视频等)通过网页或者上传工具发布到远程服务器上的过程

一、点击直接上传

<template>
  <a-upload
    v-model:file-list="fileList"
    name="file"
    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
    :headers="headers"
    @change="handleChange"
  >
    <a-button>
      <upload-outlined></upload-outlined>
      Click to Upload
    </a-button>
  </a-upload>
</template>
<script lang="ts">
import { message } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { defineComponent, ref } from 'vue';
import type { UploadChangeParam } from 'ant-design-vue';

export default defineComponent({
  components: {
    UploadOutlined,
  },
  setup() {
    const handleChange = (info: UploadChangeParam) => {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    };

    const fileList = ref([]);
    return {
      fileList,
      headers: {
        authorization: 'authorization-text',
      },
      handleChange,
    };
  },
});
</script>

二、上传前处理文件

// html:
<Upload
   :file-list="fileList"
   :max-count="1"
   :before-upload="beforeUpload"
   @remove="handleRemove"
   ><a-button type="primary" :disabled="hasFile"
   ><upload-outlined></upload-outlined>选择附件</a-button
  >
</Upload>
<a-button type="primary" @click="handleUpload">确认上传</a-button
  >

// js:
import { UploadOutlined, CloseOutlined } from '@ant-design/icons-vue';
export default defineComponent({
    components: {
          UploadOutlined,
          CloseOutlined,
    },
    setup() {
        const hasFile = ref(false);
        const fileList = ref([]);
        const beforeUpload = (file) => {
          fileList.value = [...fileList.value, file];
          hasFile.value = true;
          return false;
        };
        // 删除
      const handleRemove: UploadProps['onRemove'] = (file) => {
        const index = fileList.value.indexOf(file);
        const newFileList = fileList.value.slice();
        newFileList.splice(index, 1);
        fileList.value = newFileList;
      };
      const handleRemoveFile = async (fileName) => {
        let values = await validate();
        values.fileName = '';
        setFieldsValue({
          ...values,
        });
      };
    // 执行上传
      const handleUpload = async (params, methods) => {
        const formData = new FormData();
        let file = fileList.value[0];
        try {
          params.fileName = file.name;
          params.sampleType = sampleType.value;
          formData.append('file', file);
          formData.append('jsonStr ', JSON.stringify(params));
          await insert(formData);
          success('新增成功!!');
          emit('success');
          closeDrawer();
        } catch {
          closeDrawer();
          error('新增失败!');
          emit('error');
        }
      };
    
    },
    return {
        fileList,
        beforeUpload,
        handleRemove,
        hasFile,
        handleUpload,
    }
  })

三、自定义上传

  1. 自定义直接上传
<a-upload
    v-model:file-list="fileList"
    name="file"
    :multiple="true"
    :showUploadList="false"
    listType="text"
    :customRequest="(file) => upload(file, record)"
 >
    <a-button type="primary">上传</a-button>
</a-upload>
  1. 自定义触发后上传
// html
<a-button type="primary" @click="handleImport" class="mx-3">
   <a-upload action="" :max-count="1" :headers="headers" :customRequest="customRequest">文件上传</a-upload>
</a-button>

// js
export default defineComponent({
    components: {},
    setup() {
        // 上传文件接口
        const customRequest = async (info) => {
              const formData = new FormData();
              formData.append('excel', info.file);
              await importFile(formData);
        };
    
    },
    return {
        customRequest
    }
})

四、常用api

  • fileList:已经上传的文件列表(受控)
  • maxCount:限制上传数量。当为 1 时,始终用最新上传的文件代替当前文件
  • accept:接受上传的文件类型
  • action:上传的地址
  • beforeUpload:上传文件之前的钩子,参数为上传的文件,若返回 false 则停止上传
  • customRequest:通过覆盖默认的上传行为,可以自定义自己的上传实现
  • data:上传所需参数或返回上传参数的方法
  • status:上传状态,不同状态展示颜色也会有所不同 error | success | done | uploading | removed
最后修改:2023 年 06 月 13 日
如果觉得我的文章对你有用,请随意赞赏