上传图片
This commit is contained in:
parent
2c3f44b362
commit
b2bdaeaff3
@ -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<string> base64字符串
|
||||
*/
|
||||
static async imageToBase64(imageUri: string): Promise<string> {
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -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<HdResponse<T>>
|
||||
*/
|
||||
async uploadImage<T>(url: string, imageUrl: string): Promise<HdResponse<T>> {
|
||||
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<string, string>();
|
||||
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<T>(url, hashMap);
|
||||
} catch (error) {
|
||||
logger.error('uploadImage error:' + JSON.stringify(error));
|
||||
promptAction.showToast({ message: '图片上传失败' });
|
||||
return Promise.reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将图片转换为base64字符串
|
||||
* @param imageUri 图片URI
|
||||
* @returns Promise<string> base64字符串
|
||||
*/
|
||||
private async imageToBase64(imageUrl: string): Promise<string> {
|
||||
// 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 {
|
||||
|
||||
@ -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<UploadAvatarResponse>(
|
||||
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<string>(updateDataUrl, {
|
||||
uuid: authStore.getUser().uuid,
|
||||
userName: authStore.getUser().userName,
|
||||
photo: base64String,
|
||||
type:'2'
|
||||
} as updateExtraData).then(async (res: HdResponse<string>) => {
|
||||
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,
|
||||
|
||||
@ -37,7 +37,7 @@ struct CancelAccount {
|
||||
promptAction.showDialog({
|
||||
title: '温馨提示',
|
||||
message: '请您解除所有随访患者后再提交注销申请',
|
||||
buttons: [{ text: '取消', color: '#000000' }, { text: '确定', color: '#000000' }]
|
||||
buttons: [{ text: '确定', color: '#000000' }]
|
||||
})
|
||||
} else {
|
||||
this.uploadFeedBackAction();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user