antd for vue 使用图片上传组件

<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>
### 使用 Antd-vue 实现多文件上传 为了实现多文件上传功能,在 `main.js` 中除了引入必要的组件外,还需要确保正确配置并使用 `Upload` 组件[^1]。 下面是一个完整的示例来说明如何利用 antd-vue 创建一个多文件上传的功能: #### 修改 main.js 文件 ```javascript import Vue from 'vue'; // 引入 Upload 和其他所需组件 import { Upload, message } from 'ant-design-vue'; Vue.use(Upload); Vue.prototype.$message = message; new Vue({ render: h => h(App), }).$mount('#app'); ``` #### 编写模板部分 (template) 在对应的 `.vue` 文件内定义 HTML 模板结构: ```html <template> <a-upload name="file" :multiple="true" action="/your/upload/endpoint" @change="handleChange"> <a-button> <a-icon type="upload" /> Click to upload </a-button> </a-upload> </template> ``` 这里设置了 `name` 属性用于指定服务器端接收参数的名字;`:multiple=true` 表明允许一次选择多个文件;而 `action` 则指定了文件提交的目标 URL 地址。 #### 添加脚本逻辑 (script) 继续在同一 `.vue` 文件中编写 JavaScript 处理函数: ```javascript <script> export default { methods: { handleChange(info) { const status = info.file.status; if (status !== 'uploading') { console.log(info.file, info.fileList); } if (status === 'done') { this.$message.success(`${info.file.name} file uploaded successfully.`); } else if (status === 'error') { this.$message.error(`${info.file.name} file upload failed.`); } }, }, }; </script> ``` 此段代码实现了当文件状态改变时触发回调,并根据不同情况给出相应提示信息。 通过上述设置即可完成基于 antd-vue 的多文件上传功能。需要注意的是实际部署环境中应当替换 `/your/upload/endpoint` 为真实的 API 接口地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值