uni-app上传图片(修改用户头像)

4,279 阅读1分钟

uni-app项目开发中,在个人信息管理页面需要对用户头像信息进行管理,那么怎么实现呢?uni-app上传图片要调用uni.chooseImage()uni.uploadFile()两个api完成。在发请求时,上传图片到后台一般以formData的格式,而uni.request()携带的data格式只支持Object/String/ArrayBuffer,那么就不能使用这种方式上传。(使用vue编写,代码仅供参考)

template内容

<view class="img-boxs">
    <image :src="userInfo.avatar" @click="handleUpImg"> </image>
    <cover-view>修改头像</cover-view>
</view>

JS代码

handleUpImg() {// 点击图片区域,选择图片并上传
    uni.chooseImage({// 选择图片
        count: 1,
        success: (res) => {// 图片选择成功的回调(必传),会返回一个对象
            this.userInfo.avatar = res.tempFilePaths[0] // 用于更新视图
            uni.uploadFile({
                url: "/hospital/user/updateAvatar", // 请求地址
                filePath: res.tempFilePaths[0], // 临时文件路径
                name: "avatarfile", // 文件对应的key值
                header: {
                    type: "client" // 需要带的请求头,token等等
                },
                formData: {// 额外的请求数据
                    uesrName: this.userInfo.userName
                },
                success: (res) => {// 成功后的回调
                    console.log("修改成功");
                }
            })
        }
    })
}

CSS代码

        .img-boxs {
		width: 100px;
		height: 100px;
		border-radius: 100%;
		position: relative;
		overflow: hidden;
	}

	.img-boxs image {
		width: 100px;
		height: 100px;
		border-radius: 100%;
		margin-bottom: 10px;
	}

	.img-boxs cover-view {
		width: 100px;
		height: 40px;
		text-align: center;
		color: #fff;
		background-color: rgba(107, 96, 99, .4);
		position: absolute;
		left: 50%;
		top: 66%;
		transform: translate(-50%, 0);
	}

效果图

1.png

uni.chooseImage()uni.uploadFile()更多详细内容请参考uni-app官方文档