vue 实现文件上传、下载

vue 实现文件上传

效果图

上传成功后会在下方显示,如下图所示
在这里插入图片描述

1、使用element ui 中的el-upload

<!-- :limit="1" 限制上传数量  :drag="true" 可实现拖拽上传 :file-list会返显在下方-->
<el-upload
	class="upload-demo"
	action="#"
	:drag="true"
	:before-upload="uploadFileFun"
	:file-list="uploadFile.fileList">
	<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
	<div class="el-upload__tip fontSize12 colorRed" slot="tip">文件包括评审指南、须知及回避要求等,上传文件格式为word或pdf,文件大小在2M以内</div>
</el-upload>

2、data中定义相关数据,methods中书写上传方法

data () {
    return {
        fileIdArr: [],
        uploadFile:{
	        createUser:'',
	        createTime:'',
	        fileId: '', // 存放选择的文件
	        fileList: [],
        },
        uploadFileRules: {
          fileList: [{ required: true, message: "请上传文件", trigger: "blur" }],
        }
    }
  },
methods: {
	uploadFileFun(file){
	    var test = /(doc|docx|pdf)$/.test(file.type);
	    if (!test) {
	         this.$message.error("请上传正确的文档格式!");
	         return false;
	     }
	     const isLt2M = file.size / 1024 / 1024 < 2;
	    if (!isLt2M) {
	        this.$message.error("上传文件大小不能超过 2MB!");
	         return false;
	     }
	    // 创建formdata实例
	    let formData = new window.FormData();
	    // 将获取的文件通过append方法加入实例中
	    formData.append("file", file);
	    this.$api.
	        uploadFile(formData)
	        .then(res => {
	            // fileList用于反显
	            this.uploadFile.fileList.push(res.data)
	            this.fileIdArr.push(res.data.id)
	        })
	        .catch(err => {});
	  },
 }

3、下载

methods: {
	// 附件下载
	downloadFile(row){
		// 判断如果没有文件就不进行文件的下载
	   if (row.fileName){
	         this.$api
	         .downloadFile({fileId: row.fileId})
	         .then(res => {
	         	// 如果有文件且接口掉成功,后端会直接返回文件流,因此若返回res.code,表示接口没有返回文件流
	             if(res.code){
	                 this.$message({
	                     type: 'error',
	                     message: res.msg
	                 })
	             }else{
	             
	             	// 这里最重要,这里最重要!!!!!
	             	
	                 const link = document.createElement("a");
	                 let blob = new Blob([res]);  //文件流处理
	                 link.style.display = "none";  //去除a标签的样式
	                 // 设置链接
	                 link.href = window.URL.createObjectURL(blob);
	                 link.download = row.fileName; // 指定下载文件名,包含文件后缀
	                 document.body.appendChild(link);
	                 //模拟点击事件
	                 link.click();
	                 //移除创建的a标签
	                 window.URL.revokeObjectURL(link.href);
	                 document.body.removeChild(link);
	             }
	            
	         })
	         .catch(err => {})
	     }else{
	         this.$message({
	             message: '该邮件模板没有可下载的附件'
	         })
	     }
	 },
}

注: 也可不用file-list绑定展示上传的文件列表,重新定义自己喜欢的样式

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
文件上传下载是前端开发中非常常见的功能,Vue提供了方便的方法来实现这些功能。 文件上传Vue中可以使用第三方库vue-file-upload来实现文件上传,具体步骤如下: 1. 安装vue-file-upload ```sh npm install vue-file-upload --save ``` 2. 在组件中引入并注册vue-file-upload ```js import Vue from 'vue'; import VueFileUpload from 'vue-file-upload'; Vue.use(VueFileUpload); ``` 3. 在模板中使用vue-file-upload来实现文件上传 ```html <template> <div> <vue-file-upload url="/api/upload" @success="onUploadSuccess" @error="onUploadError" @progress="onUploadProgress" ></vue-file-upload> </div> </template> ``` 其中,url属性指定上传文件的地址,success、error和progress分别指定上传成功、上传失败和上传进度的回调函数。 文件下载Vue中可以使用原生的XMLHttpRequest对象或者第三方库axios来实现文件下载,具体步骤如下: 1. 使用XMLHttpRequest对象下载文件 ```js const xhr = new XMLHttpRequest(); xhr.open('GET', '/api/download', true); xhr.responseType = 'blob'; xhr.onload = () => { if (xhr.status === 200) { const blob = new Blob([xhr.response], { type: 'application/octet-stream' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = 'file.txt'; link.click(); URL.revokeObjectURL(url); } }; xhr.send(); ``` 其中,responseType属性指定响应类型为blob,onload事件中将响应数据转为Blob对象,并创建一个超链接来下载文件。 2. 使用axios下载文件 ```js axios({ method: 'get', url: '/api/download', responseType: 'blob', }).then((response) => { const blob = new Blob([response.data], { type: 'application/octet-stream' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = 'file.txt'; link.click(); URL.revokeObjectURL(url); }); ``` 其中,responseType属性指定响应类型为blob,然后将响应数据转为Blob对象,并创建一个超链接来下载文件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值