diff --git a/src/views/modules/news/news-publish.vue b/src/views/modules/news/news-publish.vue index efe3c869..84493ada 100644 --- a/src/views/modules/news/news-publish.vue +++ b/src/views/modules/news/news-publish.vue @@ -200,7 +200,7 @@ export default { }, watch: { 'dataForm.allDeptIdsShow': function (val) { - console.log(this.dataForm.allDeptIdsShow); + console.log(this.dataForm.allDeptIdsShow) } }, created () { @@ -441,6 +441,66 @@ export default { }, beforeAvatarUpload (file) { this.loading = true + var that = this + return new Promise((resolve, reject) => { + const isJPG = file.type === 'image/jpeg' + const isPNG = file.type === 'image/png' + const isLt1M = file.size / 1024 / 1024 < 1 + let bool = false + // 判断是否符合格式要求 + if (isJPG || isPNG) { + bool = true + } else { + that.$message.error('上传文件必须是jpg、png格式!') + return false + } + // 如果格式符合要求,但是size过大,对图片进行处理 + if (bool && !isLt1M) { + let image = new Image() + let resultBlob = '' + image.src = URL.createObjectURL(file) + image.onload = () => { + resultBlob = that.compressUpload(image) + resolve(resultBlob) + } + } else if (bool && isLt1M) { + resolve(file) + } + }) + }, + compressUpload (image) { + // 创建画布元素 + let canvas = document.createElement('canvas') + let ctx = canvas.getContext('2d') + let { width } = image + let { height } = image + canvas.width = width + canvas.height = height + ctx.fillRect(0, 0, canvas.width, canvas.height) + ctx.drawImage(image, 0, 0, width, height) + // 等比压缩 + let compressData = canvas.toDataURL('image/jpeg', 0.8) + // base64转Blob + let blobImg = this.dataURItoBlob(compressData) + return blobImg + }, + dataURItoBlob (data) { + let byteString + if (data.split(',')[0].indexOf('base64') >= 0) { + // 转二进制 + byteString = atob(data.split(',')[1]) + } else { + byteString = unescape(data.split(',')[1]) + } + let mimeString = data + .split(',')[0] + .split(':')[1] + .split('')[0] + let ia = new Uint8Array(byteString.length) + for (let i = 0; i < byteString.length; i += 1) { + ia[i] = byteString.charCodeAt(i) + } + return new Blob([ia], { type: mimeString }) }, handelError () { this.loading = false