vue文件上传和下载

文件上传

这里使用elementui组件库的文件上传组件

1.手动上传(文件选取后需点击确认上传)
  • action:上传地址
  • auto-upload:是否在选取文件后立即进行上传,默认true手动上传要将其设置为false
  • before-upload :上传文件之前的钩子,参数为上传的文件,上传格式的规定要求可在此钩子函数中写(示例中规定上传格式xlsx或xls)
  • on-success :文件上传成功时的钩子,function(response, file, fileList)
  • ref :注册DOM对象(点击确认上传时获取dom元素并进行一些操作)
<template>
	<div>
		<el-upload
		    class="upload-demo"
		     ref="uploadFile"     
		     :action="actionUrl"
		     :before-upload="beforeFileUpload"
		     :auto-upload="false"
		     :on-success='onSuccess'
		     :on-error="onError">
		     <el-button size="small" type="primary">选择文件</el-button>
		</el-upload>
		<el-button type="primary" @click="submitUpload">确认上传</el-button>
	</div>
</template>
import { BASE_URL_Manage } from 'config'
export default {  
    data () {
        return {      
          actionUrl: BASE_URL_Manage+'/webManage/upload', // 上传地址  
        }
    },
    methods:{
    	//确认上传
    	submitUpload() {
        	this.$refs.uploadFile.submit();
      	},
      	 //文件上传之前
        beforeFileUpload(file){
            const File = file.name.replace(/.+\./,"");
            if (['xlsx','xls'].indexOf(File.toLowerCase())===-1 ) {
                this.$message.error('只支持上传xlsx、xls文件格式!');
                this.$refs.uploadFile.clearFiles();
                return false;
            }            
        },
         //文件上传成功
        onSuccess(){
            this.$message.success("文件上传成功");       
        },
        //上传失败
        onError(){
             this.$refs.upload.clearFiles();
             this.$message.error("文件上传失败")
        }
    }
}
2.立即上传(文件选取后将自动上传)

上传组件去掉 auto-uploadref 即可

<template>
	<div>
		<el-upload
		    class="upload-demo"	       
		     :action="actionUrl"
		     :before-upload="beforeFileUpload"	     
		     :on-success='onSuccess'
		     :on-error="onError">
		     <el-button size="small" type="primary">上传文件</el-button>
		</el-upload>
	</div>
</template>
import { BASE_URL_Manage } from 'config'
export default {  
    data () {
        return {      
          actionUrl: BASE_URL_Manage+'/webManage/upload', // 上传地址  
        }
    },
    methods:{	
      	 //文件上传之前
        beforeFileUpload(file){
            const File = file.name.replace(/.+\./,"");
            if (['xlsx','xls'].indexOf(File.toLowerCase())===-1 ) {
                this.$message.error('只支持上传xlsx、xls文件格式!');
                this.$refs.uploadFile.clearFiles();
                return false;
            }            
        },
         //文件上传成功
        onSuccess(){
            this.$message.success("文件上传成功");       
        },
        //上传失败
        onError(){
             this.$refs.upload.clearFiles();
             this.$message.error("文件上传失败")
        }
    }
}
3.上传文件(借助el-upload组件选取文件,自行调上传接口)
  • on-change:文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用, function(file, fileList)
  • on-remove:文件列表移除文件时的钩子, function(file, fileList)
  • limit:最大允许上传文件的个数
<template>
	<div>
		<el-upload
		    class="upload-demo"
		     ref="uploadFile"     
		     :action="-"
		     :auto-upload="false" 
		     :limit="1"     
		     :on-change="onChangeFile"
			 :on-remove="onRemoveFile">
		     <el-button size="small" type="primary">选择文件</el-button>
		</el-upload>
		<el-button type="primary" @click="submitUpload">上传文件</el-button>
	</div>
</template>
import * as api from "@/api/userPage/index";
export default {  
    data () {
        return {      
          userFile: null, // 上传的文件  
        }
    },
    methods:{
    	//确认上传
    	submitUpload() {
    		if(this.userFile==null){
    			return this.$message.error("请先选取文件!"); 
    		}   			 			   		
    		//文件上传添加上传参数(若无需添加参数则直接传this.userFile给接口)
    		const formdata = new FormData();
          	formdata.append("file", this.userFile);
          	formdata.append("user","张三");	
          	//传对象参数,需转成json字符串形式
          	let tick={
          		code:"fdgfhgghg",
          		uid:"4566895623"
          	}
          	formdata.append("ssoTick",JSON.stringify(tick));	
          	//调用上传接口	
    		api.upload(formdata).then(res => {			
			    if (res.code == 200) {				
					this.$message.success("上传成功");							
				}else{
					this.$message.error(res.msg);
				}
			});      	
      	},
      	//文件上传改变
		onChangeFile(file, arr){
			//限制文件大小							
			let isLt2M = file.raw.size / 1024 / 1024 < 2;
			if(!isLt2M){
				this.$refs.uploadFile.clearFiles();
				return this.$message.error('上传文件大小不能超过 2MB!');
			}			
			this.userFile = file.raw;		
		},
		//文件移除
		onRemoveFile(){			
			this.userFile=null;
		},
    }
}

api/userPage/index.js文件

import { createService } from '@/api/fetch-auth' 
import { BASE_URL_Manage } from 'config'
var fetch = createService('Timstar')
//文件上传
export function upload (data) {
  return fetch({
    url: BASE_URL_Manage + '/targetmanager/upload',
    method: 'post',
    data,
    transformRequest(data) {
      return data;
    },
    headers: {
        "Content-Type": "multipart/form-data"
    }
  })
}

文件下载

针对文件下载请求,后端返回给前端是文件流的形式
使用 axios

axios.post(请求路径URL, {参数Params}, {
     responseType: 'blob'
     }).then(function(res){
	      //创建a标签
        let aLink=document.createElement('a');
        //兼容不同浏览器的url对象
        const URL=window.URL||window.webkitURL||window.moxURL;
        aLink.href=URL.createObjectURL(res.data);
       	//将创建的a标签添加到body中
        document.body.appendChild(aLink);
        //获取文件名
        aLink.download= decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('fileName=')[1]);
        aLink.click();
        //移除aLink节点
        document.body.removeChild(aLink);
        //销毁url对象
        URL.revokeObjectURL(aLink.href);
       }
});

需注意的几个地方

  • 设置请求返回类型, responseType: 'blob’
  • 获取文件名 headers[‘content-disposition’].split(’;’)[1].split(‘fileName=’)[1]
  • decodeURIComponent() 解码URI
    可以看看具体后端返回给你的响应头里的内容
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值