【HarmonyOS】H5 页面调用图库
作者:zhongcx
- 2024-10-09 广东
本文字数:2573 字
阅读完需:约 8 分钟
web 组件的 h5 页面调用鸿蒙 app 图库和拍照示例
1、添加权限:entry/src/main/module.json5
2、测试文件:src/main/resources/rawfile/page107.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>更换头像示例</title> <style> body { /* 确保图片不会超出屏幕宽度 */ margin: 0; padding: 0; overflow-x: hidden; } #avatarPreview { max-width: 50vw; /* 设置图片最大宽度为屏幕宽度的50% */ display: block; /* 确保图片作为块级元素显示 */ margin: 10px auto; /* 居中图片 */ } #avatarPreview img { width: 100%; /* 图片宽度自动适应其容器宽度 */ height: auto; /* 高度自适应保持图片比例 */ } </style></head><body> <h2>点击选择新头像</h2><input type="file" id="avatarInput" accept="image/*" style="margin-bottom:10px;"><button onclick="uploadAvatar()">上传头像至OSS</button><button onclick="changeAvatar()">显示头像</button> <div id="avatarPreview"></div> <script> async function uploadAvatar() { const input = document.getElementById('avatarInput'); if (input.files && input.files[0]) { // 模拟异步上传图片至OSS的过程 try { const formData = new FormData(); formData.append('file', input.files[0]); // 这里使用fetch API模拟上传请求,实际应用中需要替换为真实的服务端API地址 const response = await fetch('https://your-fake-oss-api.com/upload', { method: 'POST', body: formData }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const result = await response.json(); alert('图片上传成功!服务器响应:' + JSON.stringify(result)); } catch (error) { alert('图片上传失败:' + error); } } } function changeAvatar() { const input = document.getElementById('avatarInput'); if (input.files && input.files[0]) { const reader = new FileReader(); reader.onload = function(e) { document.getElementById('avatarPreview').innerHTML = `<img src="${e.target.result}" alt="头像预览">`; }; reader.readAsDataURL(input.files[0]); } }</script> </body></html>复制代码
3、示例代码:src/main/ets/pages/Page107.ets
import web_webview from '@ohos.web.webview';import picker from '@ohos.file.picker';import fs from '@ohos.file.fs';import { common } from '@kit.AbilityKit'; interface MyEvent { result: FileSelectorResult, fileSelector: FileSelectorParam} @Entry@Componentstruct Page107 { controller: web_webview.WebviewController = new web_webview.WebviewController(); handleFileSelection(event: MyEvent) { const PhotoSelectOptions = new picker.PhotoSelectOptions(); PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; PhotoSelectOptions.maxSelectNumber = 1; const photoPicker = new picker.PhotoViewPicker(); photoPicker.select(PhotoSelectOptions) .then((PhotoSelectResult) => { if (PhotoSelectResult.photoUris.length === 0) { console.warn('No image selected.'); return; } const srcUri = PhotoSelectResult.photoUris[0]; const context = getContext(this) as common.UIAbilityContext; const destPath = `${context.filesDir}/test${new Date().getTime()}.jpg`; try { let file = fs.openSync(srcUri, fs.OpenMode.READ_ONLY); fs.copyFileSync(file.fd, destPath); event?.result.handleFileList([destPath]); } catch (copyError) { console.error('Copying the file failed:', JSON.stringify(copyError)); } }) .catch((selectError: object) => { console.error('Failed to invoke photo picker:', JSON.stringify(selectError)); }); return true; } build() { Column() { Web({ src: $rawfile('page107.html'), // src: 'https://xxx', controller: this.controller }) .width('100%') .height('100%') .domStorageAccess(true)//设置是否开启文档对象模型存储接口(DOM Storage API)权限。 .javaScriptAccess(true)//设置是否允许执行JavaScript脚本,默认允许执行。 .databaseAccess(true)//设置是否开启数据库存储API权限,默认不开启。 .mixedMode(MixedMode.All)//HTTP和HTTPS混合 .fileAccess(true)//设置是否开启应用中文件系统的访问,默认启用。 .imageAccess(true)//设置是否允许自动加载图片资源,默认允许。 .geolocationAccess(true)//设置是否开启获取地理位置权限,默认开启。 .onlineImageAccess(true)//设置是否允许从网络加载图片资源(通过HTTP和HTTPS访问的资源),默认允许访问。 .mediaPlayGestureAccess(true)//设置有声视频播放是否需要用户手动点击,静音视频播放不受该接口管控,默认需要。 .onShowFileSelector(this.handleFileSelection.bind(this)) } .width('100%') .height('100%') }} 复制代码
划线
评论
复制
发布于: 刚刚阅读数: 7
zhongcx
关注
还未添加个人签名 2024-09-27 加入
还未添加个人简介









评论