【鸿蒙】从网页打开获取文件,并转成base64

embedded/2025/2/19 15:39:06/

 鸿蒙原生代码

import web_webview from '@ohos.web.webview';
import picker from '@ohos.file.picker';
import { BusinessError } from '@ohos.base';
import { fileIo } from '@kit.CoreFileKit';
import util from '@ohos.util';@Entry
@Component
struct UploadFile {controller:web_webview.WebviewController = new web_webview.WebviewController();@State uri: Array<string> | null = null;// // 将 ArrayBuffer 转换为 Base64 字符串// arrayBufferToBase64(buffer: ArrayBuffer): string {//   let binary = '';//   const bytes = new Uint8Array(buffer);//   for (let i = 0; i < bytes.byteLength; i++) {//     binary += String.fromCharCode(bytes[i]);//   }//   return globalThis.btoa(binary); // 使用 btoa 将二进制数据编码为 Base64// }//// btoa(binaryData: Uint8Array) {//   // 创建一个Base64Helper实例//   let base64Helper = new util.Base64Helper();//   // 使用Base64Helper将二进制数据转换为Base64编码的字符串//   return base64Helper.encodeToStringSync(new Uint8Array(binaryData));// }build() {Column(){Text('选中的图片')List(){ForEach(this.uri,(item:string)=>{ListItem(){Row(){Image(item).width('30vh').height('30vh')}}.width('30vh').height('30vh')})}.width('30vh').height('30vh')Web({src:$rawfile('setAttrAndEvent/uploadFile/index.html'),controller:this.controller}).fileAccess(false).width('100%').height('100vh').backgroundColor('grey').onShowFileSelector((event)=>{console.log('MyFileUploader onShowFileSelector invoked')let PhotoSelectOptions = new picker.PhotoSelectOptions();PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;// PhotoSelectOptions.maxSelectNumber = 5;PhotoSelectOptions.maxSelectNumber = 1;const photoPicker  = new picker.PhotoViewPicker();photoPicker .select(PhotoSelectOptions).then(async (photoSelectResult) => {this.uri = photoSelectResult.photoUris;console.info('photoPicker .select to file succeed and photoSelectResult is:' + JSON.stringify(photoSelectResult));console.info('photoPicker .select to file succeed and uri is:' + this.uri);if (this.uri.length > 0) {let oneUri = this.uri[0]// let uri: string = ''; // 这里应该是你的URIlet file = fileIo.openSync(oneUri, fileIo.OpenMode.READ_ONLY);console.info('file fd: ' + file.fd);let stat = await fileIo.stat(file.fd);// let buffer = new ArrayBuffer(4096);console.info('readSync data to file succeed and buffer size is: stat' + stat.size)let buffer = new ArrayBuffer(stat.size);let readLen = fileIo.readSync(file.fd, buffer);console.info('readSync data to file succeed and buffer size is:' + readLen);fileIo.closeSync(file);console.info('readSync data to file succeed and buffer size is: buffer 大小 ' + buffer.byteLength)// 创建一个Base64Helper实例let base64Helper = new util.Base64Helper();// 使用Base64Helper将二进制数据转换为Base64编码的字符串let base64Data = base64Helper.encodeToStringSync(new Uint8Array(buffer.slice(0, readLen)));// let base64Data = btoa(String.fromCharCode(...new Uint8Array(buffer.slice(0, readLen-1))));console.info('Base64 encoded data: ' + base64Data);}if (event) {event.result.handleFileList(this.uri);}}).catch((err: BusinessError) => {console.error(`Invoke photoPicker .select failed, code is ${err.code}, message is ${err.message}`);})return true;})}}
}

关键代码

            if (this.uri.length > 0) {
              let oneUri = this.uri[0]
              // let uri: string = ''; // 这里应该是你的URI
              let file = fileIo.openSync(oneUri, fileIo.OpenMode.READ_ONLY);
              console.info('file fd: ' + file.fd);

              let stat = await fileIo.stat(file.fd);

              // let buffer = new ArrayBuffer(4096);
              console.info('readSync data to file succeed and buffer size is: stat' + stat.size)
              let buffer = new ArrayBuffer(stat.size);
              let readLen = fileIo.readSync(file.fd, buffer);
              console.info('readSync data to file succeed and buffer size is:' + readLen);
              fileIo.closeSync(file);

              console.info('readSync data to file succeed and buffer size is: buffer 大小 ' + buffer.byteLength)


              // 创建一个Base64Helper实例
              let base64Helper = new util.Base64Helper();
              // 使用Base64Helper将二进制数据转换为Base64编码的字符串
              let base64Data = base64Helper.encodeToStringSync(new Uint8Array(buffer.slice(0, readLen)));

              // let base64Data = btoa(String.fromCharCode(...new Uint8Array(buffer.slice(0, readLen-1))));
              console.info('Base64 encoded data: ' + base64Data);

            }
 

html代码

<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>
</head>
<body>
<div class="upload"><!--  点击上传按钮   --><form id="upload-form" enctype="multipart/form-data"><input type="file" id="upload" name="upload"/></form>
</div>
</body>
</html>
<style>body{width:100%;height:auto;margin:50px auto;text-align:center;background-color:#2EB3FF}
</style>


http://www.ppmy.cn/embedded/162561.html

相关文章

中间件系列--【运维手册规范】

一、常用集群副本数设置规范 1.HDFS DataNode数量为<2,则副本数为1DataNode数量3,副本数为2DataNode数量>3,副本数为3 2.Kafka 分区数为Broker数量的1-2倍Broker数量<2,副本数为1Broker数量3,副本数为2Broker数量>3,副本数为3 3.ElasticSearch 分片数为Es Data Nod…

小米 R3G 路由器(Pandavan)实现网络打印机功能

小米 R3G 路由器&#xff08;Pandavan&#xff09;实现网络打印机功能 一、前言 家中有多台 PC 设备需要打印服务&#xff0c;但苦于家中的 Epson L380 打印机没有网络打印功能&#xff0c;并且配置 Windows 共享打印机实在是过于繁琐且需要共享机保持唤醒状态过于费电。想到…

深入解析:如何利用 Python 爬虫获取淘宝/天猫 SKU 详细信息

在电商运营中&#xff0c;SKU&#xff08;Stock Keeping Unit&#xff0c;库存单位&#xff09;详细信息是至关重要的数据。它不仅包含了商品的规格、价格、库存等关键信息&#xff0c;还直接影响到库存管理、价格策略和市场分析等多个方面。本文将详细介绍如何通过 Python 爬虫…

vue使用v-chart的实践心得

开发Vue2和Vue3时&#xff0c;我们常常需要将数据以图表的形式展示给用户&#xff0c;而 V-Chart 作为一个轻量级且易于集成的图表库&#xff0c;是 Vue 开发的首选。这篇文章&#xff0c;我将写一下关于我在使用这方面的心得。 echarts官网&#xff1a;https://echarts.apach…

网络技术介绍

一、IP地址基础 IP地址是指在网络中用于标识发送或接收数据报文设备的唯一的逻辑地址。IP地址就像现实中的地址&#xff0c;可以标识网络中的一个节点&#xff0c;数据就是通过它来找到目的地。 IP地址的主要作用&#xff1a; 标识主机或网络设备(标识其网络接口&#xff0c;提…

配置 Nginx 以支持 HTTPS

1. 安装 Nginx 如果你尚未安装 Nginx&#xff0c;请先安装&#xff1a; Ubuntu/Debian sudo apt update sudo apt install nginx -y CentOS/RHEL sudo yum install nginx -y 启动 Nginx&#xff1a; sudo systemctl enable nginx --now 2. 配置 Nginx 以支持 HTTPS &#xf…

小鹏自动驾驶 xnet 技术细节

小鹏汽车的XNet技术是其自动驾驶系统XPILOT的核心感知架构之一&#xff0c;主要应用于XPILOT 4.0及更高版本。XNet的设计目标是实现更高效的多传感器融合、动态环境建模以及实时决策能力。以下是XNet技术的关键细节和特点&#xff1a; 1. 多传感器融合与数据统一 多模态输入&am…

在软件产品从开发到上线过程中,不同阶段可能出现哪些问题,导致软件最终出现线上bug

在软件产品从开发到上线的全生命周期中&#xff0c;不同阶段都可能因流程漏洞、技术疏忽或人为因素导致线上问题。以下是各阶段常见问题及典型案例&#xff1a; 1. 需求分析与设计阶段 问题根源&#xff1a;业务逻辑不清晰或设计缺陷 典型问题&#xff1a; 需求文档模糊&#…