做项目的时候,遇到在一个组件中上传了图片,跳转到其他组件,依然需要用到该图片信息;

项目中我利用了vuex 进行状态管理,刚开始我是把上传的图片用fileReader的方式把上传的图片变成base64格式,然后存在vuex中,代码如下:

getBase64(img, callback) {

    const reader = new FileReader();

    reader.addEventListener("load", () => callback(reader.result));

    reader.readAsDataURL(img);

},

这时候就遇到第一个问题:上传大像素图片后,base64占用的空间大小几乎是图片的2倍,vuex存的方式用的是localstorage存的,无法存储超过5m的数据。

解决方法:用canvas的方式把图片压缩再获取被压缩后图片的base64格式;代码如下:

 

getBase64(file) {
      // console.log(file)
      this.fileList = [file];
      let _this = this;
      let img = document.createElement('img');
      let cvs = document.createElement('canvas');
      // let file = me.files[0];    //  获取到文件对象
      //  上传的图片大于 500KB 时才压缩
      if (file && (file.size / 1024 > 500)) {
        let reader = new FileReader();
        reader.readAsDataURL(file);     //  转成 base64 编码
        reader.onload = function (e) {
          let naturalBase64 = e.target.result;    //  获取 base64 编码,这是原图的
          img.src = naturalBase64;
          img.onload = function () {
            let ratio = img.naturalWidth / img.naturalHeight; //  获取原图比例,为了等比压缩
            cvs.width = 400;
            cvs.height = cvs.width / ratio;
            let ctx = cvs.getContext('2d');
            ctx.drawImage(img, 0, 0, cvs.width, cvs.height);    //  画在 canvas 上
            // 压缩后新图的 base64
            let zipBase64 = cvs.toDataURL();
            _this.previewImage = zipBase64;
            _this.$store.commit("search/fileList", [{ name: file.name, base64: zipBase64 }])
            _this.$store.commit("search/base64", [{ name: file.name, base64: zipBase64 }])
            // console.log(zipBase64)
          }
        }
      } else {
        let reader = new FileReader();
        reader.readAsDataURL(file);     //  转成 base64 编码
        reader.onload = function (e) {
          let naturalBase64 = e.target.result;
          _this.previewImage = naturalBase64;
          _this.$store.commit("search/fileList", [{ name: file.name, base64: naturalBase64 }])
          _this.$store.commit("search/base64", [{ name: file.name, base64: naturalBase64 }])
          // console.log(naturalBase64)
        }
      }
    },

 备注:我这里把压缩之后获取到的base64有用vuex存了,建议大数据不用vuex存,可以把大数据直接挂在到window下面,可以写成window._xxx = xxx;然后直接从window下面取;但是存在window下面 刷新页面数据就没有了;

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐