https://developer.aliyun.com/mirror/npm/package/image-conversion

npm i image-conversion --save # or yarn add image-conversion
import { compress, compressAccurately } from "image-conversion";
// 要用前先引用
 
handleBefore(file) {
      /** 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。 */
      return new Promise((resolve, reject) => {
        const _URL = window.URL || window.webkitURL;
        const isLt2M = file.size / 1024 / 1024 > 2; // 判定图片大小是否小于4MB
        // 这里需要计算出图片的长宽
        const img = new Image();
        img.onload = function() {
          file.width = img.width; // 获取到width放在了file属性上
          file.height = img.height; // 获取到height放在了file属性上
          const imgwidth = img.width > 1280; // 图片宽度
          const imgheight = img.height > 1280; // 图片高度
          // 这里我只判断了图片的宽度,compressAccurately有多个参数时传入对象
          if (imgwidth && isLt2M && imgheight) {
            compressAccurately(file, {
              size: 2048,
              width: 1280,
              height: 1280
            }).then(res => {
              resolve(res);
            });
          }  else resolve(file);
        }; // 需要把图片赋值
        img.src = _URL.createObjectURL(file);
      });
    },
 
 
再一些的浏览器上会出现一些报错  报语法错误  解决办法
  npm install babel-polyfill

1.兼容IE9/IE10可能会遇到语法或者 Promise错误,安装 babel-polyfill

npm install babel-polyfill

2.在页面入口配置main.js中引入 babel-polyfill

import 'babel-polyfill'

3.vue.config.js页面配置 disableHostCheck: true,(最后注释掉了)



  
posted on 2020-04-17 13:48  假装新手  阅读(988)  评论(0编辑  收藏  举报