van-uploader上传图片 ios旋转90度的解决方案

引入exif-js

场景:在使用vant-ui组件上传图片时,iphone手机竖屏拍的照片上传时会向左旋转90度

获取拍摄方向

EXIF.getData(file, function () {
                const orient = EXIF.getTag(this, 'Orientation')
                resolve(orient)
            })

orient为6时 iphone为竖屏拍照 使用canvas校正旋转方向

rotateImage: (image, width, height) => {
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        ctx.save()
        console.warn(width,height);
        canvas.width = width
        canvas.height = height
        ctx.rotate(0 * Math.PI / 180)
        ctx.drawImage(image, 0, 0, width, height)
        ctx.restore()
        return canvas.toDataURL("image/jpeg")
    },

ios13以上的版本才会出现这个问题,判断ios版本

ifHighThanIos13: () => {
        const userAgent = navigator.userAgent.toLowerCase();
        const ios = userAgent.match(/cpu iphone os (.*?) like mac os/);
        if (!ios) {
            return false;
        }
        const iosVersion = ios[1].replace(/_/g, '.'); // 获取ios版本
        const iosV1 = iosVersion.split('.')[0]; // 大版本号
        const iosV2 = iosVersion.split('.')[1]; // 小版本号
        if (Number(iosV1) < 13 || (Number(iosV1) === 13 && Number(iosV2) < 4)) {
            return false;
        }
        if (Number(iosV1) > 13 || (Number(iosV1) === 13 && Number(iosV2) >= 4)) {
            return true;
        }
        return false;
    }

总结

在utils中引入index.js文件

import EXIF from 'exif-js'

export default {
    getOrientation: (file) => {
        return new Promise((resolve) => {
            EXIF.getData(file, function () {
                const orient = EXIF.getTag(this, 'Orientation')
                resolve(orient)
            })
        })
    },

    dataURLtoFile: (dataurl, filename) => {
        const arr = dataurl.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
    },

    rotateImage: (image, width, height) => {
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        ctx.save()
        console.warn(width,height);
        canvas.width = width
        canvas.height = height
        ctx.rotate(0 * Math.PI / 180)
        ctx.drawImage(image, 0, 0, width, height)
        ctx.restore()
        return canvas.toDataURL("image/jpeg")
    },
    ifHighThanIos13: () => {
        const userAgent = navigator.userAgent.toLowerCase();
        const ios = userAgent.match(/cpu iphone os (.*?) like mac os/);
        if (!ios) {
            return false;
        }
        const iosVersion = ios[1].replace(/_/g, '.'); // 获取ios版本
        const iosV1 = iosVersion.split('.')[0]; // 大版本号
        const iosV2 = iosVersion.split('.')[1]; // 小版本号
        if (Number(iosV1) < 13 || (Number(iosV1) === 13 && Number(iosV2) < 4)) {
            return false;
        }
        if (Number(iosV1) > 13 || (Number(iosV1) === 13 && Number(iosV2) >= 4)) {
            return true;
        }
        return false;
    }
}

在需要调用的文件中引用

import fileUtils from "./index.js";

在van-upload的before-Read中使用

beforeRead(file) {
      return new Promise((resolve, reject) => {
        fileUtils.getOrientation(file).then(orient => {
          if (orient && orient === 6 && fileUtils.ifHighThanIos13()) {
            let reader = new FileReader();
            let img = new Image();
            reader.onload = e => {
              img.src = e.target.result;
              img.onload = function() {
                const data = fileUtils.rotateImage(img, img.width, img.height);
                const newFile = fileUtils.dataURLtoFile(data, file.name);
                resolve(newFile);
              };
            };
            reader.readAsDataURL(file);
          } else {
            resolve(file);
          }
        });
      });
    },
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
van-uploader是一款基于Vue.js的上传组件,支持单个或批量上传的功能,并且可以限制上传的文件类型、大小等参数。 使用van-uploader可以快速实现文件上传功能,以下是上传图片的实例: 1.在Vue组件中引用van-uploader组件 ``` <van-uploader action="//example.com/upload" :on-success="handleSuccess" /> ``` 其中action属性指定上传文件的地址,on-success属性指定上传成功后的回调函数。 2.定义handleSuccess函数,用于处理上传成功后的操作 ``` methods: { handleSuccess(response) { console.log(response); } } ``` 上传成功后,服务器会返回一个响应对象response,我们可以在handleSuccess函数中对返回的数据进行处理。 3.对上传组件进行配置,限制上传文件的类型、大小等属性 ``` <van-uploader action="//example.com/upload" :before-upload="beforeUpload" :max-size="5 * 1024 * 1024" accept="image/*" /> ``` 其中before-upload属性指定在上传前进行的操作,可以用来限制上传文件的类型、大小等属性,max-size属性限制上传文件的最大大小,accept属性限制上传文件的类型,此处指定只能上传图片文件。 4.在Vue实例中定义beforeUpload函数,实现上传前的参数设置 ``` methods: { beforeUpload(file) { console.log(file); const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$toast('上传图片只能是 JPG 格式!'); } if (!isLt2M) { this.$toast('上传图片大小不能超过 2MB!'); } return isJPG && isLt2M; } } ``` beforeUpload函数会在上传前调用,可以用来设置上传时的参数,这里我们实现了限制上传图片的格式和大小的功能。 以上是使用van-uploader上传图片的实例,通过简单的配置和绑定函数就可以快速实现文件上传功能,适用于各种Web项目。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值