Vue上传文件及图片的写法。

本文介绍了如何使用Element UI的上传控件,包括上传前的文件格式验证(只支持xls和xlsx),图片验证,以及上传成功后的提示消息。着重于前后端配合实现Excel文件上传功能。

1、使用element ui 上传控件(使用以下代码,主动删除错误注释)

 <el-upload action="/ordersetting/upload"    //提交后台地址
     name="excelFile"
     :show-file-list="false"
     :on-success="handleSuccess"   //上传成功后执行方法
     :before-upload="beforeUpload">  //上传前执行方法
 <el-button type="primary">上传文件</el-button>
 </el-upload>

2、上传前验证文件格式的执行方法

(1)Excel校验

//上传之前进行文件格式校验
beforeUpload(file){
   const isXLS = file.type === 'application/vnd.ms-excel';
   if(isXLS){
       return true;
   }
   const isXLSX = file.type === 'application/vnd.openxmlformats- 
   officedocument.spreadsheetml.sheet';
   if (isXLSX) {
       return true;
   }
   this.$message.error('上传文件只能是xls或者xlsx格式!');
       return false;
   }

(2)图片的校验

//上传图片之前执行
beforeAvatarUpload(file) {
	const isJPG = file.type === 'image/jpeg';
	const isLt2M = file.size / 1024 / 1024 < 2;
	if (!isJPG) {
		this.$message.error('上传图片只能是 JPG 格式!');
	}
	if (!isLt2M) {
		this.$message.error('上传图片大小不能超过 2MB!');
	}
		return isJPG && isLt2M;
}

3、上传后提示方法

//上传成功
handleSuccess(response, file) {
    if(response.flag){
        this.$message({
            message: response.message,
            type: 'success'
         });
     }else{
         this.$message.error(response.message);
     }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值