antdesignvue 多文件或单文件上传pdf和图片,加预览下载删除,限制文件大小

 <a-upload
            :customRequest="customRequest"
            :multiple="true"
            :beforeUpload="beforeFileUpload"
            name="file"
            :file-list="uploadedFileList"
            @preview="previewFile"
            :fileList="fileList"
            :remove="imgDel"
            v-decorator="['fileIds', {rules: [{required: true, message: '请上传附件!'}]}]"
          >
            <a-button><a-icon type="upload"/>上传附件</a-button>
          </a-upload>

// 上传文件
      customRequest(file) {
        //初始化文件信息
        const fileInfo = {
          uid: file.file.uid,
          name: file.file.name,
          status: 'uploading',
          response: '',
          url: ''
        }
        //放入上传列表中,以便于显示上传进度
        this.uploadedFileList.push(fileInfo)
        const formData = new FormData()
        formData.append('file', file.file)

//调用上传文件接口
        fileInfoUpload(formData).then((res) => {
          file.onSuccess(res.data, file)
          this.uploading = false
          if (res.success) {
            fileInfo.status = 'done'
            fileInfo.id = fileInfo.uid = res.data
            fileInfo.url = 'api/fileInfo/preview?id=' + res.data
            fileInfo.name = file.file.name
            this.fileList.push(fileInfo)
            this.$message.success('上传成功')
            this.setFileList()
          } else {
            fileInfo.status = 'error'
            fileInfo.response = res.msg
            this.$message.info('上传失败:' + res.message)
          }
        })
      },

        setFileList() {
        this.fileIdStrList = ''
        if (this.fileList.length > 0) {
          this.fileList.map((val, index) => {
            if (index != 0) {
              this.fileIdStrList += ','
            }
            this.fileIdStrList += val.id
          })
        }

//把fileId存到form表单中
        this.form.setFieldsValue({fileIds: this.fileIdStrList})
      },

//上传之前的操作

        beforeFileUpload(file, fileList) {
        var this_ = this
        // this.loading = true
        return new Promise((resolve, reject) => {
          const isSize= file.size  > 1*1024*1024

        //if(this.fileList.length ==1){//可以限制只上传一个文件
          //  this_.$message.error('只能上传一个文件')
            //reject(false)
          //}

const isfileType = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'application/pdf'          

         if (!isfileType ) {
            this.$message.error('请上传.jpg .png .pdf 格式的文件 ')
            reject(file)
          }
          if (isSize) {
            this_.$message.error('上传文件不能超过1M!')
            reject(false)
          }else{
            resolve(true)
          }          
        }).finally(() => {
          // this.loading = false
        })
      },

        // 预览下载
      previewFile(item) {
        if (item.name.endsWith('.jpg') || item.name.endsWith('.png')) {
          const imgWindow = window.open('')
          imgWindow && imgWindow.document.write(`<image src='${item.url}' style='display: flex; margin: 0 auto'/>`)
        } else {
          if (item.url) {

//调用下载接口
            fileInfoDownload({id: item.id}).then((res) => {
              downLoadFile(res)
            }).catch(() => {
              this.$message.error('下载错误:获取文件流错误')
            })
          }
        }
      },
      // 删除图片
      imgDel(file) {
        var index = this.fileList.indexOf(file)
        var newList = this.fileList.slice()
        newList.splice(index, 1)
        this.fileList = newList

        //调用删除图片的接口
        fileInfoDelete({id: file.id}).then(() => {
          this.uploadedFileList.splice(index, 1)
          this.setFileList()
          return true
        })
      }      

/**
 * 下载文件
 * @param {Object} res
 */
export function downLoadFile(res) {
  var blob = new Blob([res.data], {
    type: 'application/octet-stream;charset=UTF-8'
  })
  var contentDisposition = res.headers['content-disposition']
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var result = patt.exec(contentDisposition)
  var filename = result[1]
  var downloadElement = document.createElement('a')
  var href = window.URL.createObjectURL(blob) // 创建下载的链接
  var reg = /^["](.*)["]$/g
  downloadElement.style.display = 'none'
  downloadElement.href = href
  downloadElement.download = decodeURI(filename.replace(reg, '$1')) // 下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href)
}

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Ant Design Vue 3.x中的Upload组件支持多文件上传,可以通过设置`multiple`属性来实现。同时,可以通过设置`beforeUpload`属性来控制上传文件的类型和大小等限制条件。以下是一个基于Ant Design Vue 3.x的多文件上传示例: ```vue <template> <a-upload :action="uploadUrl" :headers="headers" :data="uploadData" :multiple="true" :beforeUpload="beforeUpload" @change="handleChange" > <a-button> <a-icon type="upload" /> Click to Upload </a-button> </a-upload> </template> <script> export default { data() { return { uploadUrl: 'your_upload_url', headers: { Authorization: 'Bearer ' + localStorage.getItem('token') }, uploadData: { otherParams: 'your_other_params' } } }, methods: { beforeUpload(file) { const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' if (!isJpgOrPng) { this.$message.error('You can only upload JPG/PNG file!') return false } const isLt2M = file.size / 1024 / 1024 < 2 if (!isLt2M) { this.$message.error('Image must smaller than 2MB!') return false } return true }, handleChange(info) { if (info.file.status !== 'uploading') { console.log(info.file, info.fileList) } if (info.file.status === 'done') { this.$message.success(`${info.file.name} file uploaded successfully`) } else if (info.file.status === 'error') { this.$message.error(`${info.file.name} file upload failed.`) } } } } </script> ``` 在上述示例中,我们设置了`multiple`属性为`true`,表示支持多文件上传。同时,我们通过设置`beforeUpload`属性来控制上传文件的类型和大小等限制条件。在上传文件时,我们还可以通过设置`headers`和`data`属性来传递token和其他参数。最后,我们通过监听`change`事件来获取上传文件的状态和信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值