ios上传图片旋转问题解决方案(vant上传图片)

使用 van-uploader(vant 组件库上传图片组件)上传图片时,

部分 ios 机型,会偶发从手机上传图片后,图片预览中,图片旋转了 90 度的问题。

对于该问题,vant 官网中也给出了解决方案。
但官网中的方案适配的是单选情况下,上传图片时多选图片就会报错。

不论是哪种解决方案,都用到了 Compressor 类,先引入插件。

npm install compressorjs

一 vant 官网解决方案(单选)

首先在元素中加入 before-read 属性,传入 beforeRead 方法。

<van-uploader ... before-read="beforeRead" />

在 beforeRead 方法中使用 Compressor 类对 file 进行校正处理。

...
import Compressor from 'compressorjs';
...

export default {
    
    
  ...
  methods: {
    
    
    beforeRead(file) {
    
    
      console.log('开始修正')
      return new Promise((resolve) => {
    
    
        new Compressor(file, {
    
    
          success: resolve,
          error(err) {
    
    
            console.log(err.message);
          },
        });
      })
    }
  }
}

二 完美解决方案(单选+多选)

首先在还是元素中加入 before-read 属性,传入 beforeRead 方法。

<van-uploader ... before-read="beforeRead" />

在 beforeRead 方法中使用 Compressor 类对 file 进行校正处理,这里有一点变化。

...
import Compressor from 'compressorjs';
...

export default {
    
    
  ...
  methods: {
    
    
    beforeRead(file) {
    
    
      console.log('开始修正')
      return new Promise((resolve) => {
    
    
        if(!Array.isArray(file)) file = [file]
        const filePromiseArr = file.map(item => {
    
    
          return new Promise((res) => {
    
    
            new Compressor(item, {
    
    
              success: res,
              error(err) {
    
    
                console.log(err.message);
              },
            });
          });
        })
        Promise.all(filePromiseArr).then((res) => {
    
    
          console.log('修正完毕')
          resolve(res)
        })
      }
    }
  }
}

三 体验优化

这样就可以了,但是Compressor处理是需要时间的,这时候会导致,从手机中选中图片返回页面后,照片不会立刻出现在预览区域,而是会有几秒钟的空白,这时可以为页面添加toast优化体验。

Toase.loading({
    
    
  message: '',
  forbidClick: true,
});

猜你喜欢

转载自blog.csdn.net/weixin_45809580/article/details/134802498