From b2bdaeaff395b79466dd8c97545f3a898a6055d9 Mon Sep 17 00:00:00 2001 From: xiaoxiao Date: Wed, 14 May 2025 15:28:00 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../basic/src/main/ets/utils/ChangeUtil.ets | 64 ++++++++++ commons/basic/src/main/ets/utils/request.ets | 110 ------------------ .../src/main/ets/view/EditUserDataComp.ets | 43 +++---- .../main/ets/pages/MinePage/CancelAccount.ets | 2 +- 4 files changed, 87 insertions(+), 132 deletions(-) diff --git a/commons/basic/src/main/ets/utils/ChangeUtil.ets b/commons/basic/src/main/ets/utils/ChangeUtil.ets index 4909a56..8adaf81 100644 --- a/commons/basic/src/main/ets/utils/ChangeUtil.ets +++ b/commons/basic/src/main/ets/utils/ChangeUtil.ets @@ -1,6 +1,9 @@ import HashMap from '@ohos.util.HashMap'; import { Base64Util } from './Base64Util'; import { CryptoJS } from '@ohos/crypto-js'; +import { logger } from './logger'; +import image from '@ohos.multimedia.image'; +import fs from '@ohos.file.fs'; export class ChangeUtil { @@ -54,5 +57,66 @@ export class ChangeUtil { return reg2.test(password); } + /** + * 将图片转换为base64字符串 + * @param imageUri 图片URI + * @returns Promise base64字符串 + */ + static async imageToBase64(imageUri: string): Promise { + // 1. 验证URI有效性 + if (!imageUri || !imageUri.startsWith('file://')) { + throw new Error('无效的图片URI,必须以file://开头'); + } + let imageSource: image.ImageSource | undefined; + let pixelMap: image.PixelMap | undefined; + let imagePacker: image.ImagePacker | undefined; + try { + const file = fs.openSync(imageUri, fs.OpenMode.READ_ONLY); + const imageSource = image.createImageSource(file.fd); + if (!imageSource) { + throw new Error('创建ImageSource失败,请检查图片路径'); + } + logger.info('正在获取图片信息...'); + const imageInfo = await imageSource.getImageInfo(); + logger.info(`图片尺寸: ${imageInfo.size.width}x${imageInfo.size.height}`); + pixelMap = await imageSource.createPixelMap({ + desiredSize: { + width: imageInfo.size.width, + height: imageInfo.size.height + } + }); + if (!pixelMap) { + throw new Error('创建PixelMap失败'); + } + // 5. 压缩图片 + imagePacker = image.createImagePacker(); + const packOpts: image.PackingOption = { + format: "image/jpeg", + quality: 80 // 适当提高质量保证清晰度 + }; + logger.info('正在压缩图片...'); + const arrayBuffer = await imagePacker.packing(pixelMap, packOpts); + const unit8Array = new Uint8Array(arrayBuffer); + let binary = ''; + unit8Array.forEach(byte => { + binary += String.fromCharCode(byte); + }); + const base64String = Base64Util.encodeToStrSync(binary); + logger.info(`图片转换成功,大小: ${Math.round(base64String.length / 1024)}KB`); + return base64String; + } catch (error) { + logger.error('图片处理失败: ' + JSON.stringify(error)); + throw new Error(`图片处理失败: ${error.message}`); + } finally { + // 7. 确保释放资源 + try { + pixelMap?.release(); + imageSource?.release(); + imagePacker?.release(); + } catch (e) { + logger.error('资源释放异常: ' + JSON.stringify(e)); + } + } + } } \ No newline at end of file diff --git a/commons/basic/src/main/ets/utils/request.ets b/commons/basic/src/main/ets/utils/request.ets index b3abd2c..9974151 100644 --- a/commons/basic/src/main/ets/utils/request.ets +++ b/commons/basic/src/main/ets/utils/request.ets @@ -7,8 +7,6 @@ import { HashMap } from '@kit.ArkTS'; import { CryptoJS } from '@ohos/crypto-js' import { Base64Util } from './Base64Util'; import { ChangeUtil } from './ChangeUtil' -import { BasicConstant } from '../constants/BasicConstant' -import image from '@ohos.multimedia.image'; interface HdRequestOptions { baseURL?: string @@ -270,114 +268,6 @@ class HdHttp { return ''; } } - - /** - * 上传图片方法 - * @param url 上传地址 - * @param imageUri 图片URI - * @param params 其他参数 - * @returns Promise> - */ - async uploadImage(url: string, imageUrl: string): Promise> { - try { - // 1. 读取图片文件并转换为base64 - const imageBase64 = await this.imageToBase64(imageUrl); - - // 2. 准备上传参数 - const uploadParams: UploadImageParams = { - uuid: authStore.getUser().uuid || '', - userName: authStore.getUser().userName || '', - photo: imageBase64, - type: '2' // 根据业务需求设置类型 - }; - - // 3. 转换为HashMap格式 - 使用类型安全的方式 - const hashMap = new HashMap(); - hashMap.set('uuid', uploadParams.uuid); - hashMap.set('userName', uploadParams.userName); - hashMap.set('photo', uploadParams.photo); - hashMap.set('type', uploadParams.type); - - // 4. 调用posts方法上传 - return this.posts(url, hashMap); - } catch (error) { - logger.error('uploadImage error:' + JSON.stringify(error)); - promptAction.showToast({ message: '图片上传失败' }); - return Promise.reject(error); - } - } - - /** - * 将图片转换为base64字符串 - * @param imageUri 图片URI - * @returns Promise base64字符串 - */ - private async imageToBase64(imageUrl: string): Promise { - // 1. 验证URI有效性 - if (!imageUrl || !imageUrl.startsWith('file://')) { - throw new Error('无效的图片URI,必须以file://开头'); - } - let imageSource: image.ImageSource | undefined; - let pixelMap: image.PixelMap | undefined; - let imagePacker: image.ImagePacker | undefined; - try { - // 2. 创建ImageSource(添加错误处理) - imageSource = image.createImageSource(imageUrl); - if (!imageSource) { - throw new Error('创建ImageSource失败,请检查图片路径'); - } - - // 3. 获取图片信息(添加详细日志) - logger.info('正在获取图片信息...'); - const imageInfo = await imageSource.getImageInfo(); - logger.info(`图片尺寸: ${imageInfo.size.width}x${imageInfo.size.height}`); - - // 4. 创建PixelMap - pixelMap = await imageSource.createPixelMap({ - desiredSize: { - width: imageInfo.size.width, - height: imageInfo.size.height - } - }); - if (!pixelMap) { - throw new Error('创建PixelMap失败'); - } - - // 5. 压缩图片 - imagePacker = image.createImagePacker(); - const packOpts: image.PackingOption = { - format: "image/jpeg", - quality: 80 // 适当提高质量保证清晰度 - }; - - logger.info('正在压缩图片...'); - const arrayBuffer = await imagePacker.packing(pixelMap, packOpts); - - // 6. 转换为base64 - const unit8Array = new Uint8Array(arrayBuffer); - let binary = ''; - unit8Array.forEach(byte => { - binary += String.fromCharCode(byte); - }); - - const base64String = Base64Util.encodeToStrSync(binary); - logger.info(`图片转换成功,大小: ${Math.round(base64String.length / 1024)}KB`); - return base64String; - - } catch (error) { - logger.error('图片处理失败: ' + JSON.stringify(error)); - throw new Error(`图片处理失败: ${error.message}`); - } finally { - // 7. 确保释放资源 - try { - pixelMap?.release(); - imageSource?.release(); - imagePacker?.release(); - } catch (e) { - logger.error('资源释放异常: ' + JSON.stringify(e)); - } - } - } } interface UploadImageParams { diff --git a/features/mypage/src/main/ets/view/EditUserDataComp.ets b/features/mypage/src/main/ets/view/EditUserDataComp.ets index 1d49889..cff65d3 100644 --- a/features/mypage/src/main/ets/view/EditUserDataComp.ets +++ b/features/mypage/src/main/ets/view/EditUserDataComp.ets @@ -1,4 +1,4 @@ -import { hdHttp, HdResponse,BasicConstant,ExpertData, authStore } from '@itcast/basic' +import { hdHttp, HdResponse,BasicConstant,ExpertData, authStore, ChangeUtil } from '@itcast/basic' import HashMap from '@ohos.util.HashMap' import { BusinessError } from '@kit.BasicServicesKit'; import { promptAction, router } from '@kit.ArkUI' @@ -123,28 +123,29 @@ export struct EditUserDataComp { this.photoSheetDialog = new CustomDialogController({ builder: PhotoActionSheet({ controller: this.photoSheetDialog, - onPhotoSelected: async (url: string) => { - this.photoPath = url; - console.log('Selected image URI:', url); - try { - promptAction.showToast({ message: '正在上传图片...', duration: 2000 }); - // 调用上传方法,使用明确的返回类型 - const response = await hdHttp.uploadImage( - this.updateDataUrl, - url - ); - if (response.code === 1) { - promptAction.showToast({ message: '图片上传成功' }); - console.log('上传成功,返回数据:', response.data); - // 处理上传成功后的逻辑 - // this.currentUser.avatar = response.data.avatarUrl; + onPhotoSelected: async (uri: string) => { + this.photoPath = uri; + console.info('Selected image URI:', uri); + const base64String = await ChangeUtil.imageToBase64(uri); + const updateDataUrl:string = BasicConstant.urlExpert + 'modify'; + hdHttp.post(updateDataUrl, { + uuid: authStore.getUser().uuid, + userName: authStore.getUser().userName, + photo: base64String, + type:'2' + } as updateExtraData).then(async (res: HdResponse) => { + let json:callBackData = JSON.parse(res+'') as callBackData; + if(json.code == 1 && json.data && typeof json.data === 'object') { + authStore.updateUser(json.data) + console.log('更新图片成功:', authStore.getUser().email); + promptAction.showToast({message:'头像修改成功', duration: 1000}) } else { - promptAction.showToast({ message: response.message || '图片上传失败' }); + console.error('更新图片失败:'+json.message) + promptAction.showToast({ message: json.message, duration: 1000 }) } - } catch (error) { - console.error('图片上传出错:', error); - promptAction.showToast({ message: '图片上传出错,请重试' }); - } + }).catch((err: BusinessError) => { + console.error(`更新图片请求失败: ${err}`); + }) } }), alignment: DialogAlignment.Bottom, diff --git a/products/expert/src/main/ets/pages/MinePage/CancelAccount.ets b/products/expert/src/main/ets/pages/MinePage/CancelAccount.ets index 39cda5f..42665b7 100644 --- a/products/expert/src/main/ets/pages/MinePage/CancelAccount.ets +++ b/products/expert/src/main/ets/pages/MinePage/CancelAccount.ets @@ -37,7 +37,7 @@ struct CancelAccount { promptAction.showDialog({ title: '温馨提示', message: '请您解除所有随访患者后再提交注销申请', - buttons: [{ text: '取消', color: '#000000' }, { text: '确定', color: '#000000' }] + buttons: [{ text: '确定', color: '#000000' }] }) } else { this.uploadFeedBackAction();