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-upload和customRequest方法:

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();
	},
}

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

相关推荐
程序员大阳2 小时前
副队长JavaScript教程(50)-DOM:网页开发的起点
javascript·dom·es·节点·概念·document·关系
xiaolinudao1233 小时前
给pdf文件盖骑缝章的软件有哪些
pdf
香芋芋圆6 小时前
iD-editor 详解|OSM官方在线编辑器,基于D3.js的轻量地图编辑器
开发语言·javascript·编辑器
hu55667988 小时前
如何使用Adobe Acrobat Pro DC将1页PDF切割为2页,A3变A4打印。
pdf
晗夜未央8 小时前
任务队列反复失败,先分清重试、阻塞和结果待核对
开发语言·javascript
ComPDFKit8 小时前
PDF转Word后,每行都成一段?先分清断段、文本框和扫描页
pdf·word
jktantan9 小时前
每个节点 41 字节:把一棵百万节点树拆进 14 个 typed array
前端·javascript·vue.js·算法·typescript
我命由我123459 小时前
访客系统形式(有用户概念、无用户概念)
java·开发语言·前端·javascript·python·产品运营·产品经理
程序员大阳10 小时前
副队长JavaScript教程(65)-详解JSON:轻量级数据交换格式
javascript·json·序列化·反序列化·stringify·parse
paopaokaka_luck12 小时前
基于springboot+vue的益暖微光公益服务平台(DeepSeek公益助手、善款信息追溯、志愿服务积分闭环、ECharts运营分析、活动状态自动流转)
java·前端·javascript·spring boot·mysql·架构·echarts