基于vue-upload-component封装一个图片上传组件的示例

2020-06-16 06:26:05易采站长站整理

})
imageCompressor.compress(newFile.file).then((file) => {
// 创建 blob 字段 用于图片预览
newFile.blob = ''
let URL = window.URL || window.webkitURL
if (URL && URL.createObjectURL) {
newFile.blob = URL.createObjectURL(file)
}
// 缩略图
newFile.thumb = ''
if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
newFile.thumb = newFile.blob
}
// 更新 file
this.$refs.uploader.update(newFile, {error: '', file, size: file.size, type: file.type})
}).catch((err) => {
this.$refs.uploader.update(newFile, {error: err.message || 'compress'})
})
}
}
},
remove(index, isValue) {
if (isValue) {
this.value.splice(index, 1)
this.$emit('update:value', this.value)
} else {
this.$refs.uploader.remove(this.files[index])
}
},
preview(index) {
ImagePreview({
images: this.value.map(item => (item.thumb || item.url)),
startPosition: index
});
}
}
}
</script>

图片压缩也可以自己来实现,主要是理清各种文件格式的转换


compress(imgFile) {
let _this = this
return new Promise((resolve, reject) => {
let reader = new FileReader()
reader.onload = e => {
let img = new Image()
img.src = e.target.result
img.onload = () => {
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
canvas.width = img.width
canvas.height = img.height
// 铺底色
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(img, 0, 0, img.width, img.height)

// 进行压缩
let ndata = canvas.toDataURL('image/jpeg', 0.3)
resolve(_this.dataURLtoFile(ndata, imgFile.name))
}
}
reader.onerror = e => reject(e)
reader.readAsDataURL(imgFile)
})
}
// base64 转 Blob
dataURLtoBlob(dataurl) {
let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], {type: mime})
},
// base64 转 File
dataURLtoFile(dataurl, filename) {
let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], filename, {type: mime})
}

最终效果