uniapp 上传图片
<image class="img_icon" v-if="imgSrc" :src="imgSrc" @tap="onGetImgClick"></image>
<view class="box" v-else @tap="onGetImgClick"></view>
data中定义变量imgSrc
export default {
data() {
return {
imgSrc: '',//图片地址
}
}
}
methods方法
onGetImgClick(){
const that = this
uni.chooseImage({
count: 1, // 最多可以选择的图片张数,默认9
sizeType: ['original', 'compressed'], //original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], //album 从相册选图,camera 使用相机,默认二者都有。如需直接开相机或直接选相册,请只使用一个选项
success: function(res) {
console.log('chooseImage-----》》》》》》》》', res);
//判断图片格式
let tempStr = res.tempFilePaths[0].split('.');
let lowerStr = tempStr[1].toLowerCase();
if (lowerStr != 'png' && lowerStr !== 'jpg' && lowerStr !== 'jpeg') {
uni.showToast({
title: '请上传PNG、JPG、JPEG格式的图片',
icon: 'none',
duration: 3000
});
return;
}
console.log(res.tempFiles,'beforre--------');
if(res.tempFiles[0]['size']>20*1024*1024){
uni.showToast({
title: '图片大小不能超过20M',
icon: 'none',
duration: 3000
});
return;
}
uni.showLoading({
title:'上传中...'
})
if(res.tempFiles[0]['size']<5*1024*1024){ //图片小于5M不压缩,大于5M压缩
that.uploadImgFile(res.tempFilePaths[0],that)
}else{
uni.compressImage({
src: res.tempFilePaths[0],
quality: 80,
success: res => {
console.log(res,'=========res');
that.uploadImgFile(res.tempFilePath,that)
}
})
}
}
});
},
uploadImgFile(filePath,that){
uni.uploadFile({
url: '上传图片地址',
filePath: filePath,
name: 'file',
formData: {
file: filePath
},
header: {
'Content-Type': 'multipart/form-data',
'token': 'token'
},
success: response => {
let res = JSON.parse(response.data);
console.log(res, '----res');
if (res.code == 200) {
that.showInfo = res.data
console.log('请求成功_______________', res);
// 调用下载接口
that.downloadImg(res.data.attachId);
}
},
fail: err => {
uni.hideLoading()
console.log('请求失败_______________', err);
}
});
},
// 下载图片
downloadImg(id) {
uni.downloadFile({
url: '下载图片地址',
header: {
'token': 'token',
},
success: res => {
if (res.statusCode === 200) {
console.log('下载成功');
this.imgSrc = res.tempFilePath;
uni.hideLoading()
}
}
});
}
网友评论