
uniapp上传图片前压缩图片到100kb以内
应后端要求,uniapp上传图片前需要将压缩图片到100kb以内,递归压缩,亲测有效,以此记录!
1.新建公共方法
function imageCompress(file){
return new Promise((resolve, reject)=>{
let { size,path } = file
let type = path.split(".")[1]
console.log(51,size,path,type)
//大于100kb进行压缩
if(size <= 100*1024){
resolve(file)
console.log(56,file)
return false
}
uni.compressImage({
src: path,
quality: 80,
width:'50%',
height: '50%',
success: res => {
console.log(62,res)
let newPath = res.tempFilePath+type
console.log(622,newPath)
uni.getFileInfo({
filePath:res.tempFilePath,
success:async (info)=>{
console.log(73,info)
let newFile = {...file,size:info.size,path:newPath,tempFilePath:res.tempFilePath}
resolve(await imageCompress(newFile))
}
})
},
fail:err=>{
console.log(63,err)
}
})
})
}
2.页面引入
import { imageCompress} from "@/common/commonMethods.js"
data() {
return {
file:'',
}
},
methods: {
//选择照片
select(e){
console.log(68,e)
if(e.tempFilePaths&&e.tempFiles){
this.file = e.tempFiles[0].file
this.toUpload()
}
},
// 上传照片
async toUpload(){
// 压缩图片
this.file = await imageCompress(this.file)
uni.uploadFile({
url: env.Dev.baseApi + api.upload,
filePath: this.file.tempFilePath?this.file.tempFilePath:this.file.path,
name: 'file',
success: (res) => {
console.log(146,JSON.parse(res.data));
}
});
},
}
要点:压缩图片时,宽高一定要写,否则会出现图片越压越大的情况!
更多推荐
所有评论(0)