当前位置: 首页 > article >正文

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

 鸿蒙原生代码

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 = ''; // 这里应该是你的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);

            }

            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.kler.cn/a/548514.html

相关文章:

  • 【微服务学习一】springboot微服务项目构建以及nacos服务注册
  • Python爬虫技术
  • 【推理llm论文精度】DeepSeek-R1:强化学习驱动LLM推理能力飞跃
  • 如何在Spring Boot中配置分布式配置中心
  • 消息队列概要讲解
  • uniapp-列表样式
  • 安卓基础(Adapter)
  • Redisson分布式锁和同步器完整篇
  • BeginInvoke和Invoke的使用时机
  • [环境配置] 环境配置 - Java - Apache Tomcat 安装与配置
  • Mac之JDK安装
  • NS新金融:区块链时代的财富新引擎
  • 【做一个微信小程序】校园地图页面实现
  • Dbeaver 下载mysql驱动失败
  • HTTP相关面试题
  • 机器学习:k均值
  • 2025 AutoCable 中国汽车线束线缆及连接技术创新峰会启动报名!
  • 国内外网络安全政策动态(2025年1月)
  • 【前端框架】vue2和vue3的区别详细介绍
  • Redis --- 使用 Pipeline 实现批处理操作