vueCropper 分两种方式 本地上传 和 网络图片上传(如 : CDN)
本地上传
思路: 将本地文件 file 转 base64 给cropper处理, 不会出现跨域,也不需要后端允许跨域。(一开始是将文件发给服务器再拿到URL 去处理, 实在很没必要)
步骤一: Dom : input 选择器
步骤二 : 获取file
changeUpload(e) {
this.file = e.target.files[0]
const isLt5M = this.file.size / 1024 / 1024 < 5
if (!isLt5M) {
this.$message.error(this.$t('series.upload5'))
return false
}
if (this.file) {
this.imageToBase64(this.file)
}
},
步骤三: 本地图片转base64 (如果走接口返回URL 会有跨域)
imageToBase64(file) {
var reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => {
this.result = reader.result
this.option.img = this.result
this.dialogVisible = true
}
reader.onerror = function(error) {
console.log('Error: ', error)
}
},
步骤四: 将裁剪图片给图片服务器
finish() {
// this.$refs.cropper.getCropBlob(data => {
// console.log(data)
// let files = new window.File([this.data], Date.parse(new Date()) + '.jpeg', {
// type: 'image/jpeg'
// })
// this.file = files
// console.log(this.file)
// this.applySure()
// // var fileName = 'goods' + this.fileinfo.uid
// // this.loading = true
// //上传阿里云服务器
// // client()
// // .put(fileName, data)
// // .then(result => {
// // this.dialogVisible = false
// // this.picsList.push(result.url)
// // })
// // .catch(err => {
// // console.log(err)
// // this.loading = false
// // })
// })
this.$refs.cropper.getCropData(data => {
let files = this.dataURLtoFile(data, Date.parse(new Date()) + 'my.jpeg')
this.file = files
this.$apis.user.getCertificate({ file: this.file }).then(res => {
this.backShowImg = res.data.url
})
this.dialogVisible = false
})
},
网络图片上传
前提条件: 后端图片服务器必须允许跨域 !!!!!
步骤一: 图片 URL
pfn(url) {
this.option.img = ''
this.setAvatarBase64(url, base64 => {
this.$nextTick(() => {
this.dialogVisible = true
this.option.img = base64
})
})
},
步骤二: 将图片地址转换成base64,如果不转,依旧会跨域
// 设置需要展示的图片 base64
setAvatarBase64(src, callback) {
let _this = this
let image = new Image()
// 处理缓存
image.src = src + '?v=' + Math.random()
// 支持跨域图片
image.crossOrigin = '*'
image.onload = function() {
let base64 = _this.transBase64FromImage(image)
callback && callback(base64)
}
},
// 将网络图片转换成base64格式
transBase64FromImage(image) {
let canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
let ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, image.width, image.height)
// 可选其他值 image/jpeg
return canvas.toDataURL('image/jpeg')
}
步骤三: 后续步骤和本地上传一致