<template>
<view>
<button @click="chooseImage">选择图片</button>
<button @click="uploadImage">上传图片</button>
<image v-for="(url, index) in imageList" :src="url" :key="index"></image>
</view>
</template>
<script>
export default {
data() {
return {
imageList: [],
uploadUrl: 'http://example.com/upload' // 替换成实际的上传接口地址
}
},
methods: {
//压缩
recursionCompressH5(url) {
console.log("url",url)
return new Promise((resolve, reject) => {
this.recursionCompress(url,resolve)
})
},
// 传入blob路径,.then()获取blob文件
httpRequest(src) {
let that = this
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open('GET', src, true)
xhr.responseType = 'blob'
xhr.onload = function (e) {
if (this.status == 200) {
let myBlob = this.response
let files = new window.File(
[myBlob],
myBlob.type,
{ type: myBlob.type }
) // myBlob.type 自定义文件名
resolve(files)
} else {
reject(false)
}
}
xhr.send()
})
},
recursionCompress(url,resolve) {
let that = this
uni.getImageInfo({
src: url,
success(res) {
let canvasWidth = res.width; //图片原始长宽
let canvasHeight = res.height;
let img = new Image();
console.log(res,'resinfo')
img.src = res.path;
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = canvasWidth / 2;
canvas.height = canvasHeight / 2;
ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
canvas.toBlob(function(fileSrc) {
let imgSrc = window.URL.createObjectURL(fileSrc);
uni.getFileInfo({
filePath: imgSrc,
success: (resFileInfo) => {
console.log(imgSrc, 'resFileInfo',resFileInfo)
if (resFileInfo.size > 1024 * 1024) {
//压缩后大于1M就继续压缩
console.log('再次压缩')
that.recursionCompress(imgSrc,resolve);
// indexObj.recursionCompressH5(imgSrc, callback, item);
return;
} else {
resolve(imgSrc)
}
},
});
});
}
});
},
afterRead(e) {
let _this = this
const file = e
// uni.showLoading({
// title: 'Uploading...',
// mask: true
// });
console.log("e",e)
// 遍历图片资源
file.map(item => {
console.log(item,'item')
// 进行压缩图片
this.recursionCompressH5(item).then(url =>{
console.log(url,'url')
_this.httpRequest(url).then(res => {
console.log(res,'成功转换为blob文件');
const fileReader = new FileReader()
fileReader.readAsDataURL(res) // 读取blob类型的图像文件(不是blob路径),读取成功触发onload方法,并得到result(base64格式的图片)
fileReader.onload = (event) => {
console.log(fileReader.result,'fileReader.result - base64格式');
if (fileReader.result) {
// 上传最终压缩之后的图片
_this.uploadFile(fileReader.result).then(res => {
// uni.hideLoading();
console.log(res)
// this.fileList.push(res)
}).catch(() => {
uni.hideLoading();
// this.$toast({
// title: "上传失败"
// })
})
// 调用wx_uploadImage接口,图片大小必须是1M以下,否则报错
// wx_uploadImage({
// image: fileReader.result
// }).then(res => {
// console.log('上传图片成功', res)
// this.image = res.storage_path
// })
}
}
// _this.h5_filetobase64(res); // 调用方法,把blob文件转换成base64图片
})
})
})
},
// 选择图片
chooseImage() {
uni.chooseImage({
count: 9, // 最多可选择的图片数量
success: (res) => {
this.imageList = res.tempFilePaths
// 进行压缩图片资源处理
this.afterRead(this.imageList)
}
})
},
// 上传图片
uploadFile(path) {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: this.uploadUrl,
filePath: path,
name: 'file',
header: {
token: store.getters.token
},
fileType: 'image',
cloudPath: '',
success: res => {
console.log('uploadFile res ==> ', res)
let data = JSON.parse(res.data);
if (data.code == 1) {
resolve(data.data);
} else {
reject()
}
},
fail: (err) => {
console.log(err)
reject()
}
});
});
}
}
}
</script>