vue获取file文件的宽高等属性

该博客介绍了如何在上传图片时通过JavaScript的FileReader API读取图片的宽高信息。在`handleBeforeUpload`方法中,通过创建img元素并设置其src为base64编码的图片数据,在onload事件中获取到图片的width和height,从而实现上传前检查图片尺寸的需求。
摘要由CSDN通过智能技术生成

前言:

        我们在使用上传方法的时候,是可以拿到文件的file文件的,里面有很多文件信息,比如size大小等信息,但是没有宽高这类的,那么我们上传图片经常会需要这些属性。

实现效果:

 

实现步骤:

1、核心js方法:

if (file) {
    var reader = new FileReader()
    reader.onload = function (event) {
      var base64 = event.target.result
      var img = document.createElement('img')
      img.src = base64
      img.onload = function () {
        console.log('宽度', img.width)
        console.log('高度', img.height)
      }
    }
    reader.readAsDataURL(file)
  }

2、页面与对应的js

<el-upload
    ref="uploader"
    :multiple="multiple"
    :accept="accept"
    :action="action"
    :headers="headers"
    :data="data"
    :show-file-list="false"
    :before-upload="handleBeforeUpload"   //在这里
    :on-success="handleSuccess"
    :on-error="handleError"
    :http-request="handleHttpRequest"
  > ...
 handleBeforeUpload(file) {
    //拿数据方法
      if (file) {
        var reader = new FileReader()
        reader.onload = function (event) {
          var base64 = event.target.result
          var img = document.createElement('img')
          img.src = base64
          img.onload = function () { //注意只有onload以后才可以拿到图片信息
            console.log('宽度', img.width)
            console.log('高度', img.height)
          }
        }
        reader.readAsDataURL(file)
      }

        
        //其他方法
      if (this.accept && !this.accept.includes(file.type)) {
        this.$message.error("不接受此文件类型!");
        return false;
      }

      if (this.sizeLimit && file.size > this.sizeLimit * 1024 * 1024) {
        this.$message.error(`文件大小不能超过 ${this.sizeLimit}MB!`);
        return false;
      }
}

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值