uniapp-上传图片预览图片

5次阅读

共计 1273 个字符,预计需要花费 4 分钟才能阅读完成。

<view class="setting-item">
    <text class="item-title" @click="preview"> 头像 </text>
    <view class="item-right" @click="changeImg">
    <!-- userinfo.headimgurl 是用户登陆的头像也就是未更改时的头像 changeimg 是用户更改后的头像 -->
    <image class="headimgsize" :src="userinfo.headimgurl || changeimg" mode=""></image>
    <i class="iconfont">&#xe625;</i>
    </view>
</view>
data() {
    return {changeimg: '', // 更改后的头像}
},
// 获取 vuex 的数据
computed: mapState({userinfo: state => state.userinfo}),
methods: {changeImg() {
        uni.chooseImage({success: (chooseImageRes) => {
                const tempFilePaths = chooseImageRes.tempFilePaths;
                this.changeimg = tempFilePaths[0] 
                uni.uploadFile({
                    url: app.apiUrl+'small/index/indexdata', // 仅为示例,非真实的接口地址
                    filePath: tempFilePaths[0],
                    name: 'headimgurl',
                    formData: {openid: uni.getStorageSync('openid')
                    },
                    success: (res) => {console.log(JSON.parse(res.data))
                        var res = JSON.parse(res.data)
                        if (res.status) {app.getUserData() // 这里调用用户信息接口更新数据存进 vuex
                            uni.showToast({
                                title:res.msg,
                                icon:'none',
                                duration:2000
                            })
                        }else {
                            uni.showToast({
                                title:res.msg,
                                icon:'none',
                                duration:2000
                            })
                        }
                    }
                });
            }
        });
    },
}

预览图片:我把点击事件放在“头像”,点击头像可预览图片,实际应用中是不会这么设计的哈

preview(){
    uni.previewImage({urls: [this.userinfo.headimgurl],// 拿 vuex 中的头像地址
        longPressActions: {itemList: ['发送给朋友', '保存图片', '收藏'],
            success: function(data) {console.log('选中了第' + (data.tapIndex + 1) + '个按钮, 第' + (data.index + 1) + '张图片');
            },
            fail: function(err) {console.log(err.errMsg);
            }
        }
    });
}

正文完
 0