uniapp implements avatar upload function

uniapp implements avatar upload function

step:

It is roughly divided into the following 3 steps
1. Click to trigger an event
2. Select a picture
3. Upload through the interface

1. Event triggering
<view class="info_list" @click="chooseImage">
			<p>头像</p>
			<view>
				<image :src="userInfo.image" mode=""></image>
				<uni-icons type="arrowright" size="18" color="#A4A4A4"></uni-icons>
			</view>	
		</view>
2. Call the uni method in the eventuni.chooseImage(OBJECT)

Official document linkhttps://uniapp.dcloud.io/api/media/image?id=chooseimage

	chooseImage(){
    
    
		uni.chooseImage({
    
    
			count:1,//限制最大上传图片数量
			sizeType: ['original', 'compressed'],//图片压缩还是原图
			success: (res) => {
    
    
			//图片选择成功的回调
			//res中返回一个图片本地的临时地址
					console.log(res)
				}
			)}
2. Call the uni method in the eventuni.uploadFile(OBJECT)

Official document link:https://uniapp.dcloud.io/api/request/network-file?id=uploadfile

chooseImage(){
    
    
				uni.chooseImage({
    
    
					count:1,
					sizeType: ['original', 'compressed'],
					success: (res) => {
    
    
						const tempFilePaths =res.tempFilePaths//图片临时数组
						console.log(tempFilePaths)
						uni.uploadFile({
    
    
						//请求的url接口地址
							url:'http://192.168.3.195:8080/api/member/member/uploadHeadImage',
							formData:{
    
    
								//请求中接口额外的参数
								id:'1385048044696801281'
							},
							fileType:'image',//图片类型
							filePath:tempFilePaths[0],//哪张图片
							name:'file',//对应接口的文件名称
							header:{
    
    //请求头
								"Content-Type": "multipart/form-data"
							},
							success:(res)=>{
    
    
							//成功的回调
								//一般用于重新获取数据渲染页面
								console.log(res)
							},
							fail:(err)=>{
    
    
							//失败的回调
								console.log(err)
							}
						})
					}
				})
			},

Guess you like

Origin blog.csdn.net/qq_51075057/article/details/117334827