antd for vue 使用图片上传组件

这段代码展示了如何使用Ant Design的<a-upload>组件实现图片上传功能,包括限制上传数量、文件类型、大小,以及预览、删除和上传图片到服务器的逻辑。同时,它还包含了一个图片预览的模态框,用于展示所选图片。
<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 大文件视频分片上传功能 在前端开发中,上传大文件(如超过 1GB 的视频)时,直接上传可能会导致请求超时、服务器压力大、网络中断等问题。为了解决这些问题,通常采用 **分片上传(Chunked Upload)** 技术。Ant Design Vue 提供了 `a-upload` 组件,可以灵活地自定义上传逻辑,非常适合实现分片上传功能。 #### 1. 分片上传的基本原理 分片上传的核心思想是将一个大文件切分为多个小块(chunk),然后逐个上传这些小块。服务器端需要能够接收这些分片,并在所有分片上传完成后进行合并。其流程如下: - 客户端将文件切分为多个 chunk; - 每个 chunk 包含文件名、分片索引、总分片数等元信息; - 每个 chunk 单独上传到服务器; - 服务器接收所有分片后,合并为完整文件。 #### 2. 使用 Ant Design Vue 实现分片上传 Ant Design Vue 的 `a-upload` 组件支持 `customRequest` 属性,可以完全自定义上传逻辑。以下是实现分片上传的关键步骤: ##### 2.1 设置 `beforeUpload` 钩子 在上传之前,检查文件类型和大小,避免非视频文件上传。 ```javascript beforeUpload(file) { const isValidType = ['video/mp4', 'video/ogg', 'video/webm'].includes(file.type); if (!isValidType) { this.$message.error('只能上传视频文件'); return false; } return true; } ``` ##### 2.2 实现 `customRequest` 方法 在该方法中,将文件切分为多个 chunk,并逐个上传。 ```javascript async customRequest(options) { const { file, onProgress, onSuccess, onError } = options; const chunkSize = 1024 * 1024 * 5; // 每个分片 5MB let chunkIndex = 0; const totalChunks = Math.ceil(file.size / chunkSize); const uploadChunk = async (start, end, index) => { const chunk = file.slice(start, end); const formData = new FormData(); formData.append('file', chunk); formData.append('fileName', file.name); formData.append('chunkIndex', index); formData.append('totalChunks', totalChunks); try { const response = await fetch('/api/upload-chunk', { method: 'POST', body: formData, }); const result = await response.json(); onProgress({ percent: (index / totalChunks) * 100 }); if (index < totalChunks - 1) { await uploadChunk(end, end + chunkSize, index + 1); } else { onSuccess(result); } } catch (err) { onError(err); } }; await uploadChunk(0, chunkSize, 0); } ``` ##### 2.3 使用 `a-upload` 组件 在模板中使用 `a-upload` 并绑定 `customRequest` 和 `beforeUpload`。 ```vue <template> <a-upload :customRequest="customRequest" :beforeUpload="beforeUpload" :showUploadList="false" > <a-button>上传视频</a-button> </a-upload> </template> ``` #### 3. 服务器端处理分片上传 服务器端需要提供以下接口: - `/api/upload-chunk`:接收单个分片; - `/api/merge-chunks`:合并所有分片为完整文件。 示例伪代码(Node.js + Express): ```javascript app.post('/api/upload-chunk', (req, res) => { const { chunkIndex, totalChunks, fileName } = req.body; const chunkPath = `./uploads/${fileName}.part${chunkIndex}`; fs.writeFileSync(chunkPath, req.file.buffer); res.json({ success: true }); }); app.post('/api/merge-chunks', (req, res) => { const { fileName, totalChunks } = req.body; const writeStream = fs.createWriteStream(`./uploads/${fileName}`); for (let i = 0; i < totalChunks; i++) { const chunkPath = `./uploads/${fileName}.part${i}`; const chunk = fs.readFileSync(chunkPath); writeStream.write(chunk); fs.unlinkSync(chunkPath); } writeStream.end(); res.json({ success: true }); }); ``` #### 4. 支持断点续传和进度条 为了实现断点续传,可以在客户端记录已上传的分片索引,并在上传前检查服务器是否已存在该分片。进度条可以通过 `onProgress` 回调实时更新。 #### 5. 大文件上传优化策略 - **并发上传**:使用 Promise.all 控制并发上传的分片数量,提高效率; - **重试机制**:为失败的分片添加重试逻辑; - **暂停/继续**:记录当前上传状态,实现暂停和继续功能; - **上传速度估算**:根据已上传数据量和时间估算剩余时间。 #### 6. 移动端适配 在移动端上传大视频文件时,建议限制最大上传大小,并提供清晰的进度提示和错误处理机制,以提升用户体验。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值