新手必看:鸿蒙DevEco Studio Harmony OS5-图片上传
·
图片上传
由于鸿蒙系统的隐私安全保护,应用无法直接从系统相册中获取到图片,所以鸿蒙系统的图片上传流程主要有以下几步:
- 通过鸿蒙官方的API唤起系统相册,让用户将需要上传的图片选中并返回其在内存中的临时路径
- 通过临时路径我们将图片拷贝到应用的沙箱中
- 通过上传文件的API将应用沙箱中的图片文件进行上传
主要API有以下几个
@ohos.file.photoAccessHelper (相册管理模块)
@ohos.file.fs (文件管理)
@ohos.request (上传下载)
1. 选择图片
使用系统图片选择器
import picker from '@ohos.file.picker';
async function selectImage() {
try {
const photoSelectOptions = new picker.PhotoSelectOptions();
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
photoSelectOptions.maxSelectNumber = 1; // 选择一张图片
const photoPicker = new picker.PhotoViewPicker();
const result = await photoPicker.select(photoSelectOptions);
if (result && result.photoUris && result.photoUris.length > 0) {
return result.photoUris[0]; // 返回选择的图片URI
}
} catch (err) {
console.error(`Failed to select image. Code: ${err.code}, message: ${err.message}`);
}
return null;
}
2. 获取图片文件
import fs from '@ohos.file.fs';
async function getImageFile(uri: string) {
try {
const file = await fs.open(uri, fs.OpenMode.READ_ONLY);
const stat = await fs.stat(uri);
const buffer = new ArrayBuffer(stat.size);
await fs.read(file.fd, buffer);
await fs.close(file.fd);
return buffer;
} catch (err) {
console.error(`Failed to read image file. Code: ${err.code}, message: ${err.message}`);
}
return null;
}
3. 上传图片到服务器
import http from '@ohos.net.http';
async function uploadImage(imageData: ArrayBuffer, uploadUrl: string) {
const httpRequest = http.createHttp();
try {
const requestOptions = {
method: http.RequestMethod.POST,
header: {
'Content-Type': 'multipart/form-data'
},
extraData: {
'file': imageData,
'otherParams': 'value' // 其他表单参数
}
};
const response = await httpRequest.request(uploadUrl, requestOptions);
if (response.responseCode === http.ResponseCode.OK) {
console.info('Upload successful:', response.result);
return response.result;
} else {
console.error(`Upload failed with status: ${response.responseCode}`);
}
} catch (err) {
console.error(`Upload error: Code: ${err.code}, message: ${err.message}`);
} finally {
httpRequest.destroy();
}
return null;
}
4. 完整流程示例
async function uploadImageProcess() {
// 1. 选择图片
const imageUri = await selectImage();
if (!imageUri) {
console.error('No image selected');
return;
}
// 2. 获取图片文件
const imageData = await getImageFile(imageUri);
if (!imageData) {
console.error('Failed to read image file');
return;
}
// 3. 上传图片
const uploadUrl = 'https://your-server.com/api/upload';
const result = await uploadImage(imageData, uploadUrl);
if (result) {
// 上传成功处理
console.info('Image upload completed successfully');
} else {
// 上传失败处理
console.error('Image upload failed');
}
}
注意事项
- 权限申请:在config.json中声明所需权限
"reqPermissions": [
{
"name": "ohos.permission.READ_MEDIA",
"reason": "To read image files"
},
{
"name": "ohos.permission.INTERNET",
"reason": "To upload images to server"
}
]
-
大文件处理:对于大图片,考虑使用分块上传或压缩后再上传
-
UI反馈:上传过程中应提供进度反馈和状态提示
-
错误处理:妥善处理各种可能的错误情况(网络问题、权限问题等)
-
安全考虑:如果上传敏感信息,确保使用HTTPS协议
更多推荐
所有评论(0)