Uniapp选择和上传头像

// 选择头像
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,这里两种都允许
			sourceType: ['album', 'camera', 'poster'], // 可以指定来源是相册、相机还是临时文件,这里三种都允许
			success: (res) => {
				const {errMsg,tempFilePaths,tempFiles}=res
				if(errMsg!='chooseImage:ok'){
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
					return
				}
				// 进行上传图片
				uni.uploadFile({
					url: `${baseurl}/file/upload`, // 后端用于处理图片并返回图片地址的接口
					method: 'POST', // 请求方法,根据后端接口要求选择GET或POST
					header: {
						"Content-Type": "multipart/form-data" , // formdata提交格式
					},
					filePath: tempFilePaths[0],
					name: 'file', // 后端服务器接收上传文件的字段名,默认为'file'
					formData: { // 其他的formdata参数
						fileType: '2',
						uid: '10001',
						fileContainerName: 'default'
					},
					success: (res) => {
						const {code,data:{name,url}} = JSON.parse(res.data); // 返回的是字符串,需要转成对象格式
						if(code!=0){
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
							return
						}
						// 进行更新仓库
						consumerStore.userInfo.avatar = url; // 将图片地址保存到用户信息中
					},
					fail: () => {
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						})
					}
				});
				
				
			}
		});

### 实现 UniApp上传本地相对路径的头像图片到服务器 在 UniApp 中实现将本地相对路径的头像图片上传至服务器涉及多个步骤,包括选择文件、处理文件路径以及通过 `uni.uploadFile` 发送请求。 #### 使用 uni.chooseImage 选择图片 为了允许用户选择上传的图片,可以使用 `uni.chooseImage` 方法来打开相册或相机选取图片。此方法返回所选图片的信息列表,其中包含临时文件路径: ```javascript async chooseAvatar() { const res = await new Promise((resolve, reject) => { uni.chooseImage({ count: 1, sizeType: ['compressed'], sourceType: ['album', 'camera'], success: resolve, fail: reject }); }); if (res.tempFilePaths.length === 0) return; console.log('Selected image:', res.tempFilePaths[0]); } ``` #### 处理并上传图片 一旦选择了图片,则可以通过调用 `uni.uploadFile` 来执行实际的上传操作。需要注意的是,在某些情况下可能还需要设置额外参数如表单字段等。下面是一个完整的例子展示如何完成这一过程[^1]: ```javascript async uploadAvatar(tempFilePath) { try { let result = await new Promise((resolve, reject) => { uni.uploadFile({ url: 'https://example.com/upload', // 替换成自己的服务端API地址 filePath: tempFilePath, name: 'file', formData: { user: 'test' }, success: resolve, fail: reject }) }); console.log('Upload succeeded!', JSON.parse(result.data)); } catch(error){ console.error('Failed to upload file.', error); } } // 绑定按钮点击事件触发上述两个函数 <template> <button @click="handleClick">Choose and Upload Avatar</button> </template> <script> export default { methods: { async handleClick(){ const path = await this.chooseAvatar(); if(path){ await this.uploadAvatar(path); } } } }; </script> ``` 对于那些希望直接显示在线资源而不是本地存储中的图像的情况,可以在项目配置中定义一个公共前缀用于构建绝对 URL 地址[^2]: ```javascript Vue.prototype.localImgSrc = function(img){ return "https://yourdomain.com/static/images/" + img; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值