上传图片如果过大,等待时间过长体验不好,于是使用js压缩图片再上传,无关图片清晰度。
/** * 压缩图片 * @param file 图片文件 * @param callback 回调函数,压缩完要做的事,例如ajax请求等。 */ compressFile(file,callback){ let fileObj = file; let reader = new FileReader() reader.readAsDataURL(fileObj) //转base64 reader.onload = function(e) { let image = new Image() //新建一个img标签(还没嵌入DOM节点) image.src = e.target.result image.onload = function () { let canvas = document.createElement('canvas'), // 新建canvas context = canvas.getContext('2d'), imageWidth = image.width / 4, //压缩后图片高度和宽度 imageHeight = image.height / 5, data =''; canvas.width = imageWidth canvas.height = imageHeight context.drawImage(image, 0, 0, imageWidth, imageHeight) data = canvas.toDataURL('image/jpeg',0.1) // 0.1压缩至以前的0.1倍 let arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1], // 转成blob bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } let files = new window.File([new Blob([u8arr], {type: mime})], 'test.jpeg', {type: 'image/jpeg'}) // 转成file callback(files) // 回调 } }},图片压缩完毕后就会毁掉callback函数
上传拿到文件进行判断大小是否需要压缩。需要压缩就使用压缩方法,通过回调函数进行操作。
这里需要特别注意,因为我使用的是iview,一直习惯了this方法调用函数,如果在这里函数调用函数的话,此this非彼this,所以就需要使用$this来进行接收外面的this,从而调用外面的uploads函数方法。
依赖阿里云的
<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk.min.js"></script>封装密钥
进行图片上传
参数分别是文件名字,和文件