Vue使用cube-ui的upload组件实现图片压缩

1,524 阅读4分钟

本文首发于:webug.io

简介

cube-ui是滴滴的一款基于Vue.js 实现的精致移动端组件库

官方文档地址:didi.github.io/cube-ui/#/z…

快速使用

我们在使用cube-ui之前首先需要npm进行安装

npm install cube-ui --save

注意:此安装部分只针对于 vue-cli < 3 的情况

安装完成之后需要在main.js里面import一下

import Cube from 'cube-ui'
Vue.use(Cube);

接下来在页面中就可以调用cube-ui的组件了!!!

示例

<cube-upload
    ref="upload"
    :simultaneous-uploads="1"
    :max = "5"
    :auto="false"
    @files-added="filesAdded"
    @file-removed = "filesRemoved"
/>
  • simultaneous-uploads 上传并发数
  • max 最多可选择多少张
  • auto 是否自动上传
  • files-added 选择完图片回调方法
  • file-removed 删除图片回调方法

更多方法参数可见:didi.github.io/cube-ui/#/z…

具体方法实现
data(){
    return{
        imgList:[]
    }
}


// 这里的files是一个文件的数组
filesAdded(files) {
    let hasIgnore = false;
    const limitSize = 1 * 1024;
    // 最大5M
    const maxSize = 5 * 1024 * 1024;
    for (let i = 0; i< files.length; i++) {
      const file = files[i];
      // 如果选择的图片大小最大限制(这里为5M)则弹出提示
      if(file.size > maxSize){
        file.ignore = true;
        hasIgnore = true;
        break;
      }
      // 如果选择的图片大小大于1M则进行图片压缩处理(Base64)
      if(file.size > limitSize){
        this.compressPic(file);
      }else{
        let reads= new FileReader();
        reads.readAsDataURL(file);
        let that = this;
        reads.onload = function(e) {
          var bdata = this.result;
          that.imgList.push(bdata)
        }
      }
    }
    hasIgnore && this.$createToast({
      type: 'warn',
      time: 1000,
      txt: '图片最大支持5M'
    }).show()
},

// 图片压缩方法
compressPic(file){
    let reads= new FileReader();
    reads.readAsDataURL(file)
    // 注意这里this作用域的问题
    let that = this;
    reads.onload = function(e) {
      var bdata = this.result;
      // 这里quality的范围是(0-1)
      var quality = 0.1;
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      var img = new Image();
      img.src = bdata;
      img.onload =function() {
        var width = img.width;
        canvas.width = width;
        canvas.height = width * (img.height / img.width);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        let data = canvas.toDataURL("image/jpeg",quality);
        that.imgList.push(data)
      }
    };
  }

压缩完成之后放入imgList数组中...

捋一下大概的逻辑,其实非常简单:

  1. 前台选择完成图片会进入filesAdded方法回调中
  2. 在filesAdded主要做了两个判断:一是选择图片的大小不得超过5M,二则是如果选择的图片大于1M则进行压缩,否则不进行。
  3. 将压缩过的base64代码放入imgList数组中去

这个时候我们的数据已经拿到了,接下来要做的就是上传到后台去。

submit(){
    const sendData = {
        imgList : this.imgList
    }
    this.remotePost('/upload', sendData, (rsp)=> {
         // 上传成功后的业务逻辑
    }
}

后台代码

@RequestMapping("/upload", method=RequestMethod.POST)
@ResponseBody
public RspEntity imgUpload(HttpSession session, @RequestBody Map<String, Object> reqData) throws Exception {
    // 图片列表
    List<String> imgList = (List<String>)reqData.get("imgList");
    
    // 通过for循环取出list中的base64代码
    for(String imgBase64 : imgList){
        // 可通过base64转file/byte[]等根据业务自行实现
    }
}

另外一种方式通过后台进行压缩

data(){
    return{
        fileList: new FormData()
    }
}

filesAdded(files) {
    for (let k in files) {
      const file = files[k];
      this.existFile = file;
      this.fileList.append('files',file);
    }
}

submit(){
    this.remotePost('/upload', this.fileList, (rsp)=> {
         // 上传成功后的业务逻辑
    }
}

这样搞就是传参就是file类型的...

后台代码则需要进行以下改造...

@RequestMapping("/upload", method=RequestMethod.POST)
@ResponseBody
public RspEntity imgUpload(HttpSession session, @RequestParam(value="files") MultipartFile[] files) throws Exception {
	for (int i = 0; i < files.length; i++) {
		MultipartFile file = files[i];
		String fileType = file.getContentType();
		if(StringUtils.isEmpty(fileType) || !fileType.matches("image.*")){
			logger.error("上传图片类型错误:" + fileType);
			rspEntity.setRspMsg("上传图片类型错误");
			rspEntity.setRspCode(AppConstants.MSG_STATUS_FAIL);
			return rspEntity;
		}
		if(file.getSize() > (long)(5 * 1024 * 1024)){
			logger.error("上传图片大小超过限制:" + file.getSize());
			rspEntity.setRspMsg("上传图片大小超过限制");
			rspEntity.setRspCode(AppConstants.MSG_STATUS_FAIL);
			return rspEntity;
		}
		String fileName = file.getOriginalFilename();
		String temp[] = fileName.split("\\.");
		if (temp.length < 2 || !temp[temp.length - 1].matches("(jpg|jpeg|png|JPG|JPEG|PNG)")) {
			logger.error("上传图片文件名错误:" + fileName);
			rspEntity.setRspMsg("上传图片文件名错误");
			rspEntity.setRspCode(AppConstants.MSG_STATUS_FAIL);
			return rspEntity;
		}
		byte[] imgCompress = CommUtil6442.compressPicForScale(file.getBytes(), 300, file.getOriginalFilename());
		// 具体根据业务实现
    }
}

这里是通过谷歌的一个图片压缩工具compressPicForScale,具体方法如下:

/**
	 * 根据指定大小压缩图片
	 *
	 * @param imageBytes
	 *            源图片字节数组
	 * @param desFileSize
	 *            指定图片大小,单位kb
	 * @param imageId
	 *            影像编号
	 * @return 压缩质量后的图片字节数组
	 */
	public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize, String imageId) {
		if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {
			return imageBytes;
		}
		long srcSize = imageBytes.length;
		double accuracy = getAccuracy(srcSize / 1024);
		try {
			while (imageBytes.length > desFileSize * 1024) {
				ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
				Thumbnails.of(inputStream).scale(accuracy).outputQuality(accuracy).toOutputStream(outputStream);
				imageBytes = outputStream.toByteArray();
			}
			logger.info("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb", imageId, srcSize / 1024,
					imageBytes.length / 1024);
		} catch (Exception e) {
			logger.error("【图片压缩】msg=图片压缩失败!", e);
		}
		return imageBytes;
	}

	/**
	 * 自动调节精度(经验数值)
	 *
	 * @param size
	 *            源图片大小
	 * @return 图片压缩质量比
	 */
	private static double getAccuracy(long size) {
		double accuracy;
		if (size < 900) {
			accuracy = 0.85;
		} else if (size < 2047) {
			accuracy = 0.6;
		} else if (size < 3275) {
			accuracy = 0.44;
		} else {
			accuracy = 0.4;
		}
		return accuracy;
	}

使用之前需要在pom.xm里面引入,如果不是maven项目则需要去网上搜索下载

<dependency>
	<groupId>net.coobird</groupId>
	<artifactId>thumbnailator</artifactId>
	<version>0.4.8</version>
</dependency>

遇到的坑

我们在使用上传插件的时候,如果不是自动上传,则需要将action删除掉,不能将其设置为:action="#",否则会请求两次。