#鸿蒙通关秘籍#HarmonyOS Next 如何实现从手机选择图片或拍照上传功能?

HarmonyOS
2024-11-28 16:01:46
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
hm673ff0fbd0c6a

要实现从手机选择图片或拍照并上传到服务器的功能,可采用以下步骤:

  1. 首先,检查并申请媒体读取和写入权限。
  2. 使用 @ohos.file.photoAccessHelper 模块提供的接口从相册选择图片。
  3. 通过 @ohos.multimedia.cameraPicker 模块启动拍照功能。
  4. 将所选图片或拍摄的照片复制到应用的缓存目录中,以便于上传。
  5. 使用 request.uploadFile API 上传图片到指定的服务器地址。
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import camera from '@ohos.multimedia.camera';
import camerapicker from '@ohos.multimedia.cameraPicker';
import { request } from '@kit.BasicServicesKit';

// 从手机相册选择图片
function selectImageFromGallery() {
    const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    photoSelectOptions.maxSelectNumber = 1;

    const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
    photoViewPicker.select(photoSelectOptions).then(async (photoSelectResult) => {
        if (photoSelectResult.photoUris.length) {
            await uploadImage(photoSelectResult.photoUris[0]);
        }
    }).catch((error) => {
        console.error(`Failed to select image: ${error.message}`);
    });
}

// 拍照功能
async function capturePhoto() {
    const pickerProfile = { cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK };
    try {
        const pickerResult = await camerapicker.pick(this.context, [camerapicker.PickerMediaType.PHOTO], pickerProfile);
        if (pickerResult?.resultUri) {
            await uploadImage(pickerResult.resultUri);
        }
    } catch (error) {
        console.error(`Failed to capture photo: ${error.code}`);
    }
}

// 上传图片
async function uploadImage(filePath) {
    const uri = `internal://cache/${filePath}`;
    const uploadConfig = {
        url: 'http://your-upload-url.com',
        method: "POST",
        files: [{ filename: filePath, name: "file", uri, type: "image/jpeg" }],
        data: []
    };
    
    try {
        const uploadTask = await request.uploadFile(this.context, uploadConfig);
        
        uploadTask.on('progress', (size, total) => {
            console.log(`Upload progress: ${size}/${total}`);
        });

        uploadTask.on('headerReceive', (data) => {
            console.info(`Upload success: ${JSON.stringify(data)}`);
        });

        uploadTask.on('complete', (taskStates) => {
            console.info(`Upload completed`);
        });

        uploadTask.on('fail', (taskStates) => {
            console.error(`Upload failed: ${JSON.stringify(taskStates)}`);
        });
    } catch (e) {
        console.error(`Upload error: ${JSON.stringify(e)}`);
    }
}
分享
微博
QQ
微信
回复
2024-11-28 15:49:19
相关问题
如何HarmonyOS实现图片上传功能
183浏览 • 0回复 待解决
HarmonyOS Web 图片上传功能失效
199浏览 • 1回复 待解决
Web组件如何实现文件上传功能
384浏览 • 1回复 待解决
进入相册拍照选择图片做头像
13530浏览 • 2回复 已解决
HarmonyOS如何实现图片上传
429浏览 • 1回复 待解决