a-upload组件实现文件的上传——.pdf,.ppt,.pptx,.doc,.docx,.xls,.xlsx,.txt

实现下面的上传/下载/删除功能:要求支持:【.pdf,.ppt,.pptx,.doc,.docx,.xls,.xlsx,.txt】

分析上面的效果图,分为【上传】按钮和【文件列表】功能:

解决步骤1:上传按钮

直接上代码:

js 复制代码
 <a-upload
  multiple
  :showUploadList="false"
  :before-upload="beforeUpload"
  :customRequest="customRequest"
  :remove="handleRemove"
  accept=".pdf,.ppt,.pptx,.doc,.docx,.xls,.xlsx,.txt"
>
  <a-button type="primary">
    <a-icon type="upload" /> 点击上传
  </a-button>
</a-upload>

1.multiple:多选,可以实现多个文件同时选中进行上传

2.showUploadList:上传后的文件列表要不要展示,由于我需要自定义文件列表,所以这个属性设置为false

3.before-upload:上传之前的函数,可以判断文件的类型限制和文件大小限制,此处只限制文件类型

4.customRequest:自定义上传函数

5.remove:删除文件的函数------此处无意义

6.accept:上传的文件格式限制

下面写一下before-uploadcustomRequest方法:

js 复制代码
 beforeUpload(file) {
  const isValidType = [
    'application/pdf',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'text/plain',
  ].includes(file.type);
  if (!isValidType) {
    this.$message.error('只支持 PDF、PPT、Word、Excel 和 TXT 格式的文件');
  }
  return isValidType;
},
async customRequest(data) {
  const formData = new FormData();
  formData.append('file', data.file);
  const resData = await uploadFile(formData).then((res) => {
    return res;
  });
  console.log(5555, resData);
  if (resData) {
    this.fileList.push({
      uid: encodeURI(this.ossUrl + resData),
      name: resData.data.split(/[/\\]/).pop(),
      status: 'done',
      url: encodeURI(this.ossUrl + resData),
      checked:false,
    });
    this.$forceUpdate();
  }
},

解决步骤2:文件列表功能

js 复制代码
<div v-if="fileList.length">
 <div class="btnCls">
   <a-space>
     <a-checkbox v-model="allChecked" @change="onAllCheckChange">全选</a-checkbox>
     <a href="javascript:;" style="color:#67C23A" @click="batchDownLoad">批量下载</a>
     <a href="javascript:;" style="color:red;" @click="batchDelete">批量删除</a>
   </a-space>
 </div>
 <div v-for="item in fileList" :key="item.uid" style="margin-top:5px;">
   <a-checkbox v-model="item.checked" @change="onCheckChange($event,item)">
   </a-checkbox>
   <a href="javascript:;" style="margin:0 10px;">{{item.name}}</a>
   <a-space>
     <a href="javascript:;" style="color:#67C23A" @click="downloadFile(item.url,item.name)">下载</a>
     <a href="javascript:;" style="color:red;" @click="handleDelete(item)">删除</a>
   </a-space>
 </div>
</div>

对应的代码如下:

js 复制代码
data(){
	return{
		allChecked:false,
		fileList:[],
	}
},
methods:{
 	onAllCheckChange(e){
      this.allChecked = e.target.checked;
      this.fileList.forEach(item=>{
        item.checked = e.target.checked;
      })
      this.$forceUpdate();
    },
    onCheckChange(e,item){
      item.checked = e.target.checked;
      this.$forceUpdate();
      let arr = this.fileList.filter(file=>file.checked);
      if(arr.length==0){
        this.allChecked = false;
      }else if(arr.length==this.fileList.length){
        this.allChecked = true;
      }
    },
    handleDelete(item){
      //删除文件
      let index = this.fileList.findIndex(file=>file.url==item.url);
      if(index>-1){
        this.fileList.splice(index,1);
      }
      if(this.fileList.length==0){
        this.allChecked = false;
      }
    },
    batchDelete(){
      let arr = this.fileList.filter(item=>item.checked);
      if(arr.length==0){
        this.$message.info('请选择要删除的文件');
        return;
      }
      arr.forEach(item=>{
        this.handleDelete(item);
      })
    },
    batchDownLoad(){
      let arr = this.fileList.filter(item=>item.checked);
      if(arr.length==0){
        this.$message.info('请选择要下载的文件');
        return;
      }
      arr.forEach(item=>{
        this.downloadFile(item.url,item.name);
      })
    },
    //下载文件
	downloadFile(url, fileName) {
	    const downloadRes = async ()=>{
	        try {
	            let response = await fetch(url);
	            let blob = await response.blob();
	            let objectURL = window.URL.createObjectURL(blob);
	            let a = document.createElement('a');
	            a.href = objectURL;
	            a.download = fileName;
	            a.click();
	            a.remove();
	            window.URL.revokeObjectURL(objectURL);
	        }catch (e) {
	            var element = document.createElement('a');
	            element.setAttribute('href', url);
	            element.setAttribute('download', fileName);
	            document.body.appendChild(element);
	            element.click();
	            document.body.removeChild(element);
	        }
	    }
	    downloadRes();
	},
}

完成!!! 多多积累,多多收获!!!

相关推荐
yanlele15 分钟前
我用爬虫抓取了 25 年 5 月掘金热门面试文章
前端·javascript·面试
烛阴2 小时前
void 0 的奥秘:解锁 JavaScript 中 undefined 的正确打开方式
前端·javascript
初遇你时动了情2 小时前
腾讯地图 vue3 使用 封装 地图组件
javascript·vue.js·腾讯地图
dssxyz2 小时前
uniapp打包微信小程序主包过大问题_uniapp 微信小程序时主包太大和vendor.js过大
javascript·微信小程序·uni-app
heart000_13 小时前
128K 长文本处理实战:腾讯混元 + 云函数 SCF 构建 PDF 摘要生成器
人工智能·自然语言处理·pdf
开开心心_Every3 小时前
便捷的Office批量转PDF工具
开发语言·人工智能·r语言·pdf·c#·音视频·symfony
ohMyGod_1234 小时前
React16,17,18,19新特性更新对比
前端·javascript·react.js
@大迁世界4 小时前
第1章 React组件开发基础
前端·javascript·react.js·前端框架·ecmascript
一瓣橙子4 小时前
7.7日 实验03-Spark批处理开发(2)
开发语言·javascript·ajax
Hilaku5 小时前
从一个实战项目,看懂 `new DataTransfer()` 的三大妙用
前端·javascript·jquery