2019-02-28 前端图片压缩

github 地址:

https://github.com/xkeshi/image-compressor


使用步骤:

1.  npm 安装

npm install image-compressor.js

2.  引入

import ImageCompressor from 'image-compressor.js' // 引入

3.  读取 

HTML

JS

document.getElementById('file').addEventListener('change', (e) => {  

        // 读取文件

       const file = e.target.files[0];  

      if (!file) { 

            return;     // 为空处理

         } 

        //  文件压缩

  new ImageCompressor(file, {    

    quality: .6,  //压缩百分点   -->0  文件越小

    success(result) {      

        const formData = new FormData(); // FormData学习地址 https://developer.mozilla.org/zh-CN/docs/Web/API/FormData

      formData.append('file', result, result.name);      // 通过XMLHttpRequest服务发送压缩的图像文件-Send the compressed image file to server with XMLHttpRequest.

    //接口请求发送给后台  ***参数为FormData

        axios.post('/path/to/upload', formData).then(() => {        console.log('Upload success');

      });

作者:UYOU

链接:https://www.imooc.com/article/40038

来源:慕课网

    },

    error(e) {      

        console.log(e.message);

        },

  });

});

你可能感兴趣的:(2019-02-28 前端图片压缩)