vue 实现文件上传、下载

vue 实现文件上传

效果图

上传成功后会在下方显示,如下图所示
vue 实现文件上传、下载_第1张图片

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绑定展示上传的文件列表,重新定义自己喜欢的样式

你可能感兴趣的:(vue.js,javascript,ecmascript)