图片上传

This commit is contained in:
xiaoxiao
2025-05-13 17:25:26 +08:00
parent 3d1c988435
commit ab1f72ba6c
12 changed files with 627 additions and 84 deletions
+120 -18
View File
@@ -8,6 +8,7 @@ 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
@@ -175,7 +176,6 @@ class HdHttp {
return this.request<T>(url, http.RequestMethod.POST, data)
}
httpReq<T>(url: string, datas: HashMap<string, string>): Promise<HdResponse<T>> {
// 创建httpRequest对象。
let httpRequest = http.createHttp();
let url1 = "https://dev-app.igandan.com/app/manager/getSystemTimeStamp";
@@ -204,29 +204,22 @@ class HdHttp {
datas.set("client_type", 'A');
datas.set("version",'4.0.0' );
datas.set('timestamp',tp+'');
return this.posts<T>(url, datas);
}
else
{
} else {
return this.posts<T>(url, datas);
}
}
).catch((err:BusinessError) => {
logger.info('Response httpReq error:' + JSON.stringify(err));
return Promise.reject(err);
}).finally(() => {
httpRequest.destroy()
})
}
httpReqSimply<T>(url: string) {
httpReqSimply<T>(url: string) {
// 创建httpRequest对象。
let httpRequest = http.createHttp();
let promise = httpRequest.request(
// 请求url地址
url,
@@ -248,16 +241,14 @@ class HdHttp {
const result = data.result as HdResponse<T>
return result
}
).catch((err:BusinessError) => {
logger.info('Response httpReq error:' + JSON.stringify(err));
return Promise.reject(err);
}).finally(() => {
httpRequest.destroy()
})
}
getSign(extraDatas1:HashMap<string, string>): string {
let secret= extraDatas1.get("timestamp")
if(secret!=null) {
@@ -275,14 +266,125 @@ class HdHttp {
let Md5keyValueStr: string = CryptoJS.MD5(keyValueStr).toString();
let base64Str:string=Base64Util.encodeToStrSync(Md5keyValueStr);
return base64Str;
}
else
{
} else {
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 {
uuid:string,
userName:string,
photo:string,
type:string
}
export const hdHttp = new HdHttp({ baseURL: '' })