鸿蒙NEXT上传图片功能PhotoViewPicker核心功能解析 #ArkTS#鸿蒙Next#HarmonyOS SDK应用服务#HarmonyOS 语言
PhotoViewPicker
是鸿蒙系统中用于媒体资源选择的核心组件,通过它可以便捷地实现图片、视频等媒体文件的选择功能。下面从基本用法、参数配置到高级应用进行全面解析:
一、PhotoViewPicker 基础用法
PhotoViewPicker 的使用流程主要分为三步:
- 创建实例
- 配置参数
- 启动选择器获取结果
以下是最基本的使用示例:
typescript
import photoAccessHelper from "@ohos.photoAccess.photoAccessHelper";
async function pickImage() {
try {
// 1. 创建选择器实例
const picker = photoAccessHelper.createPhotoViewPicker();
// 2. 配置选择参数(此处使用默认配置)
const options = {
MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE, // 只选择图片
maxSelectNumber: 1, // 最多选择张数
isSearchSupported: true, // 显示搜索
isPhotoTakingSupported: true, // 支持拍照
recommendationOptions: true, // 智能推荐
preselectedUris: true, // 预览文件
isPreviewForSingleSelectionSupported: true, // 单选是否支持预览
};
// 3. 启动选择器并获取结果
const selectedAssets = await picker.select(options);
if (selectedAssets.photoUris.length) {
// 处理选择的资源
console.info("选择的资源:", selectedAssets.photoUris);
}
} catch (error) {
console.error("选择图片失败:", error);
}
}
二、关键参数详解
PhotoViewPicker 的参数配置非常灵活,可以根据需求定制选择器的行为:
typescript
const options = {
MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE, // 只选择图片
maxSelectNumber: 1, // 最多选择张数
isSearchSupported: true, // 显示搜索
isPhotoTakingSupported: true, // 支持拍照
recommendationOptions: true, // 智能推荐
preselectedUris: true, // 预览文件
isPreviewForSingleSelectionSupported: true, // 单选是否支持预览
};
三、MIMEType 参数深度解析
MIMEType
参数是 PhotoViewPicker 中非常强大的一个配置项,它允许你精确控制选择器中显示的文件类型:
typescript
// 示例1:只允许选择JPEG和PNG图片
IMAGE_TYPE = 'image/*',
// 示例2:只允许选择视频文件
VIDEO_TYPE = 'video/*',
// 示例3:
MOVING_PHOTO_IMAGE_TYPE = 'image/movingPhoto'
// 示例4:允许所有
IMAGE_VIDEO_TYPE = '*/*',
四、处理选择结果
选择器返回的结果是一个 PhotoSelectResult
对象,包含以下关键属性:
typescript
class PhotoSelectResult {
/**
* The uris for the selected files.
*
* @type { Array<string> }
* @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
* @since 10
*/
/**
* The uris for the selected files.
*
* @type { Array<string> }
* @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
* @atomicservice
* @since 11
*/
/**
* The uris for the selected files.
*
* @type { Array<string> }
* @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
* @crossplatform
* @atomicservice
* @since 12
*/
photoUris: Array<string>;
/**
* Original option.
*
* @type { boolean }
* @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
* @since 10
*/
/**
* Original option.
*
* @type { boolean }
* @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
* @atomicservice
* @since 11
*/
/**
* Original option.
*
* @type { boolean }
* @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
* @crossplatform
* @atomicservice
* @since 12
*/
isOriginalPhoto: boolean;
}
- 获取到资源后,通常需要进行以下处理:
- 使用文件 URI 读取文件内容
- 进行必要的格式转换(如压缩图片)
- 上传到服务器或保存到本地
ts
// 这里以oss上传为例
// uri为选择图片路径
import { http } from '@kit.NetworkKit';
import fs from '@ohos.file.fs'
import { request } from '@kit.BasicServicesKit';
export async function upload (uri: string): Promise<string> {
// 此处从服务器获取
const data = {
policy: 'qweqwe',
signature: 'qweqwe',
ossAccessKeyId: 'qweqwe',
host: 'https://???/api',
};
const name = Date.now() + '.' + uri.split('.').pop();
const key = `${new Date().getFullYear()}/${name}`
const context = getContext();
// 通过getContext获取沙箱地址
const destPath = `${context.cacheDir}/${name}`;
const file = fs.openSync(uri);
// 将文件复制一份到沙箱缓存地址,这一步尤为重要,只有沙箱地址的文件可以进行上传操作
fs.copyFileSync(file.fd, destPath);
const result = await request.uploadFile(context,{
// files字段是上传的文件组成的列表,类型为formData
files: [{ filename: 'file', name: 'file', uri: `internal://cache/${name}`, type: 'image/jpeg' }],
// data字段是携带的参数,建议把类型设置为formData
data: [
{ name: 'name', value: `${name}`, },
{ name: 'policy', value: `${data.policy}` },
{ name: 'OSSAccessKeyId', value: Object.values(data)[2] },
{ name: 'signature', value: `${data.signature}` },
{ name: 'key', value: key },
],
method: http.RequestMethod.POST,
header: {
Accept: '*/*',
// 设置header确保参数类型为FormData
"Content-Type": "multipart/form-data"
},
// 请求地址
url: data.host
});
return new Promise((res, rej) => {
result.on('progress', (u, t) => {
console.log('进度', u / t);
});
result.on('complete', e => {
console.log('ok', JSON.stringify(e));
res(`${data.host + key}`);
});
result.on('fail', e => {
console.log('错误', JSON.stringify(e));
rej(e);
})
});
}
五、注意事项与常见问题
- 权限要求 需要在 config.json 中声明文件访问权限:
json
{
"requestPermissions": [
{
"name": "ohos.permission.READ_MEDIA",
"reason": "需要访问媒体文件"
}
]
}
-
文件处理注意
-
- 系统媒体库中的文件 URI 通常是临时的,建议复制到应用私有目录再使用
ts
const name = Date.now() + "";
const key = `${new Date().toLocaleDateString()}/${name}`;
const context = getContext();
const destPath = `${context.cacheDir}/${name}`;
const file = fileIo.openSync(uri);
fileIo.copyFileSync(file.fd, destPath);
console.log(destPath);
-
大文件处理时建议进行异步操作,避免 UI 卡顿
-
request.uploadFile文件上传时候一直报错 401
-
兼容性注意:
-
- 不同鸿蒙版本的 API 可能存在差异,建议在开发前查阅对应版本的官方文档
-
- 部分参数(如 title、initialDirectory)可能只在特定版本中支持
-
通过合理配置 PhotoViewPicker 的各项参数,开发者可以轻松实现符合需求的媒体选择功能,为应用增色不少。