<template>
<view>
<!-- 背景图片 -->
<view class="bg-default" v-if="imgBg === ''" @click="chooseImg()">
<view class="" style="width: 70rpx; height: 70rpx;">
<image class="my_img" :src="avatarUrl"></image>
</view>
<view class="text-default">添加背景图片</view>
</view>
<view class="add_img_view" v-else>
<view class="add_img_item" @click="bindImg()">
<image :src="imgBg"></image>
<view class="add_close" @click.stop="deleteImg()">
<uni-icons type="clear" size="15" color="#4977F9"></uni-icons>
</view>
</view>
</view>
</view>
</template>
<script>
export default{
data() {
return {
// 上传默认图片
avatarUrl: '../../static/myCheck/default.png',
// 背景图展示
imgBg: '',
// 背景图预览
imgBgArray: [],
// 背景图路径
imgBgArr: '',
// 上传的背景临时路径
imgBgUrl: '',
// 上传的背景图绝对路径
imgBgArrUrl: '',
}
},
methods:{
// 选择背景图片
chooseImg() {
const isIosTrue = uni.getStorageSync('IOS_FIRST_CAMERA')
if (this.phoneType === 'ios' && isIosTrue !== 'false') {
// 设为false就代表不是第一次开启相机
uni.setStorageSync('IOS_FIRST_CAMERA', 'false')
}
uni.chooseImage({
sizeType: "compressed",
// 选择图片的数量
count: 1,
success: res => {
// console.log(res.tempFilePaths[0])
this.imgBg = res.tempFilePaths[0]
this.imgBgArray = res.tempFilePaths
this.app_img(0, res)
},
})
},
// 图片压缩
//(这里实际上一开始是要求选择多张图片的,所以将res作为一个数组进行的处理,
// 后期需求变更,写的比较急,就没改,直接给num传了一个0,默认从数组第一个开始,
// 然后通过判断数组的length来直接return掉。)
app_img(num, res) {
let that = this
if (Number(num) === Number(res.tempFiles.length)) {
return
}
let index = res.tempFiles[num].path.lastIndexOf(".")
let img_type = res.tempFiles[num].path.substring(index, res.tempFiles[num].path.length)
let img_yuanshi = res.tempFiles[num].path.substring(0, index)
let d2 = new Date().getTime()
plus.zip.compressImage({
src: res.tempFiles[num].path,
dst: img_yuanshi + d2 + img_type,
quality: 10
}, function(e) {
that.imgBgArr = e.target
that.postImg(that.imgBgArr)
that.app_img(num + 1, res)
})
},
// 删除图片
deleteImg() {
this.imgBg = ''
this.imgBgAr = ''
this.imgBgArrUrl = ''
},
// 点击图片
bindImg() {
if(this.imgBgArray.length !== 0){
console.log(index)
uni.previewImage({
urls: this.imgBgArray,
current: 0
})
}
},
// 上传图片
postImg(imgFilePaths) {
uni.uploadFile({
url: baseUrl.apiUrl + '/xxx/xxx',
filePath: imgFilePaths,
name: 'file',
success: (uploadFileRes) => {
let imgValue = JSON.parse(uploadFileRes.data)
this.imgBgArrUrl = imgValue.data.absoluteUrl
this.imgBgUrl = imgValue.data.url
}
});
},
}
}
</script>
<style>
</style>
uniapp 上传图片功能
最新推荐文章于 2025-03-21 15:33:22 发布