antd for vue 使用图片上传组件

这段代码展示了如何使用Ant Design的<a-upload>组件实现图片上传功能,包括限制上传数量、文件类型、大小,以及预览、删除和上传图片到服务器的逻辑。同时,它还包含了一个图片预览的模态框,用于展示所选图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
      <a-form-item label="图片上传(最多上传9张)" >
        <a-upload
          name="file"
          list-type="picture-card"
          :file-list="fileList"
          :showUploadList="true"
          data-type="jpg|png|jpeg"
          ref="files"
          :before-upload="beforeUpload"
          @change="handleChange"
          :remove="handleRemove"
          @preview="handlePreview"
          multiple
          style="margin-left: 10%"
        >
          <div v-if="fileList.length < 9" id="container">
            <a-icon type="plus" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </a-form-item>
</template>

<script>
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)
  })
}
export default {
  data () {
    return {
      visible: false,
      // 中国地域城市code集合
      fileList: [],
      flag: true,
      previewVisible: false,
      previewImage: ''
    }
  },
  methods: {
    // 关闭模态框(图片预览)
    handleCancel () {
      this.previewImage = ''
      this.previewVisible = false
    },
    // 打开模态框(图片预览)
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    // 删除照片
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
      this.Product.images.splice(index, 1)
      this.flag = false
    },
    // 上传图片之前的校验
    beforeUpload (file) {
      if (this.fileList.length === 10) {
        this.$message.warn('只能上传9个文件')
        const newFileList = this.fileList.slice()
        newFileList.splice(-1, 7)
        this.fileList = newFileList
      } else {
        this.fileList = [...this.fileList, file]
      }
      // 获得允许上传的文件类型
      var type = this.$refs.files.$attrs['data-type']
      for (let item of this.fileList) {
        var exName = item.name.split('.')[1]
        if (type.indexOf(exName) === -1) {
          this.$message.error('请检查文件类型,只允许上传图片文件')
          const index = this.fileList.indexOf(file)
          this.fileList.splice(index, 1)
          break
        }
        // 判断文件大小
        if (item.size / 1024 / 1024 > 20) {
          this.$message.error('上传文件大小不能超过20MB')
          break
        }
      }
      return false
    },
    // 上传图片方法
    handleChange (file) {
      // 当删除的时候会触发onchange事件 因此使用flag控制onchange事件
      if (this.flag === true) {
        const formData = new FormData()
        formData.append('file', file.file)
        this.fileList = file.fileList
        this.$upload(methods, formData).done((res) => {
          if (res.data.code === '500') {
            this.$message.error(res.data.message)
            this.fileList = []
            this.Product.images = []
          }
          if (res.data.code === '200') {
            this.$message.success(res.data.message)
            this.Product.images.push(res.data.data)
          }
        })
      } else {
        this.flag = true
      }
    }
  }
}
</script>
在Ant Design Vue的`a-upload`组件中,当你需要同时上传多个文件并只发送一次请求时,可以使用`action`属性配合`beforeUpload`和`onPreview`钩子函数来处理。默认情况下,每次点击“上传”按钮,`a-upload`都会触发一次HTTP请求。为了解决这个问题,你可以: 1. **合并文件**:在`beforeUpload`钩子中检查是否所有文件都准备好了,只有当所有文件都准备好时才允许上传。例如,可以设置一个计数器,每个文件上传成功就减一,直到全部上传完毕。 ```javascript <template> <a-upload :list-type="listType" :action="uploadUrl" :multiple="true" :before-upload="(file) => handleBeforeUpload(file)"> <a-button>选择文件</a-button> </a-upload> </template> <script> export default { methods: { handleBeforeUpload(file) { // 检查是否所有文件都准备好 if (this.uploadingFiles.length === this.files.length - 1) { return false; } // ... 其他文件处理逻辑,如验证、添加到数组等 }, // 真正的上传方法 uploadFile(file) { this.uploadingFiles.push(file); // 发起实际的异步上传请求,此处省略具体实现 }, }, data() { return { files: [], // 存储所有选中的文件 uploadingFiles: [], // 当前正在上传的文件列表 uploadUrl: 'your/upload/api', // 服务器接收文件的URL }; }, } </script> ``` 2. **一次性请求**:在用户完成所有文件选择之后,通过`this.$nextTick`确保DOM更新后再发送请求。这通常配合状态管理库(如Vuex)或者自定义事件来实现。 ```javascript handleAllFilesUploaded() { this.$nextTick(() => { const formData = new FormData(); for (let file of this.uploadingFiles) { formData.append('files', file); } this.uploadFile(formData); // 调用真正的API发送请求 this.uploadingFiles = []; // 清空已上传文件列表 }); }, ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值