HarmonyOS h5 web上传图片,文件的demo

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
shlp

参考下面伪代码

// 1.首先通过前端页面调用应用侧函数,
class testClass {
  constructor() {
  }

  uploadImage(): void{

  }
}
@Entry
@Component
struct WebComponent {
  webviewController: webview.WebviewController = new webview.WebviewController();
  // 声明需要注册的对象
  @State testObj: testClass = new testClass();

  build() {
    Column() {
      // Web组件加载本地index.html页面
      Web({ src: $rawfile('index.html'), controller: this.webviewController})
        // 将对象注入到web端
        .javaScriptProxy({
          object: this.testObj,
          name: "testObjName",
          methodList: ["uploadImage"],
          controller: this.webviewController
        })
    }
  }
}

//html
<!-- index.html -->
  <!DOCTYPE html>
  <html>
  <body>
  <button type="button" onclick="callArkTS()">Click Me!</button>
  <p id="demo"></p>
  <script>
  function callArkTS() {
    let str = testObjName.uploadImage();
  }
  </script>
  </body>
  </html>

  //第二步进行文件上传
  function uploadImage(): string {
    let uri = '';
    let photoViewPicker = new picker.PhotoViewPicker();
    let photoSelectOption = new picker.PhotoSelectOptions();
    photoSelectOption.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
    photoViewPicker.select(photoSelectOption).then((photoSelectResult) => {
      console.log("photoSelectResult:" + photoSelectResult);
      uri = photoSelectResult.photoUris[0];
      console.log("uri:" + uri);
      try {
        let resultPhoto = fs.openSync(uri, fs.OpenMode.READ_ONLY);
        let resultName = resultPhoto.name;
        let fileTemp = fs.openSync(getContext().filesDir + resultPhoto.name, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
        let imageUri = fileTemp.path;
        fs.copyFileSync(resultPhoto.fd, fileTemp.fd);
        fs.closeSync(resultPhoto);
        fs.closeSync(fileTemp);
        const httpRequest = http.createHttp();
        httpRequest.request(uploadUrl, {
          method: http.RequestMethod.POST,
          header: {
            'Content-Type': 'multipart/form-data',
            'Connection': 'keep-alive'
          },
          expectDataType: http.HttpDataType.ARRAY_BUFFER,
          multiFormDataList: [
            {
              name: 'file',
              contentType: 'image/jpg',
              filePath: imageUri,
              remoteFileName: 'file.jpg'
            },
          ],
        }, (err, data) => {
          console.log('上传结束')
          httpRequest.destroy();
        }
        )
      } catch (err) {
        console.error(`tag:Failed to request the upload. err: ${JSON.stringify(err)}`);
      }

    }).catch((err: BusinessError) => {
      console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
    })
    return uri;
  }
@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  //定义一个全局的string类型的数组,用来存放通过picker拉起后选择完图片后图片的uri
  @State uris: Array<string> = []
  @State base64Str : string = ""
  @State testObj: testClass = new testClass(this.base64Str);
  aboutToAppear() {
    web_webview.WebviewController.setWebDebuggingAccess(true);
  }
  build() {
    Column() {

      Web({ src: $rawfile('TestonShowFileSelector.html'), controller: this.controller })
        .javaScriptAccess(true)
        .domStorageAccess(true)
        .onShowFileSelector((event) => {
          // //-------调用相册-------------------------
          console.log('MyFileUploader onShowFileSelector invoked')
          const photoSelectOptions = new picker.PhotoSelectOptions();
          // 过滤选择媒体文件类型为IMAGE_VIDEO_TYPE
          photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE;
          // 选择媒体文件的最大数目
          photoSelectOptions.maxSelectNumber = 8;
          //let uris: Array<string> = [];
          const photoViewPicker = new picker.PhotoViewPicker();
          photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
            this.uris = photoSelectResult.photoUris;
            let file1 = fs.openSync(this.uris[0])
            let array:ArrayBuffer = new ArrayBuffer(fs.statSync(file1.fd).size)
            fs.readSync(file1.fd,array)
            let unit = new Uint8Array(array)
            let base64 = new util.Base64Helper();
            let mystr = base64.encodeToStringSync(unit);
            this.base64Str = "myFunction(\"" + mystr + "\")"
            this.controller.runJavaScript(this.base64Str)
            console.info('photoViewPicker.select to file succeed and uris are:' + this.uris);//file://media/Photo/11/IMG_1713942933_005/IMG_20240424_151353.jpg
          }).catch((err: BusinessError) => {
            console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
          })

          return false
          //----调用文件管理器-----------------
          // console.log('MyFileUploader onShowFileSelector invoked')
          // const documentSelectOptions = new picker.DocumentSelectOptions();
          // // 选择媒体文件的最大数目
          // documentSelectOptions.maxSelectNumber = 2;
          // const documentViewPicker = new picker.DocumentViewPicker();
          // documentViewPicker.select(documentSelectOptions).then((DocumentSelectResult: Array<string>) => {
          //   this.uris = DocumentSelectResult;
          //   console.info('photoViewPicker.select to file succeed and uris are:' + this.uris);
          // }).catch((err: BusinessError) => {
          //   console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
          // })
          // return false

          ////-----相机--------------------------------
          // const context = getContext(this) as common.UIAbilityContext
          // context.startAbilityForResult({
          //   action:"ohos.want.action.imageCapture",
          //   parameters:{
          //     callBundleName:"com.hm.imageshow"
          //   }
          // }).then((res)=>{
          //   console.log("testTag - " +JSON.stringify(res));
          //   let str:string = res.want?.parameters!["resourceUri"] as string
          //   console.log("str"+str);//file://media/Photo/11/IMG_1713942933_005/IMG_20240424_151353.jpg
          //   let fd = fs.openSync(str).fd
          //   this.uris[0] = str
          //   let arr:ArrayBuffer = new ArrayBuffer(128)
          //   fs.readSync(fd,arr)
          //   console.log("testTag - " + str);
          //
          // })
          //return false
        })

    }
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS h5客服无法上传相册图片
28浏览 • 1回复 待解决
HarmonyOS web组件加载h5h5拉起摄像头
615浏览 • 1回复 待解决
HarmonyOS webH5交互
744浏览 • 1回复 待解决
H5图片Web组件中显示异常
287浏览 • 1回复 待解决
H5原生调JSbrigedemo示例
251浏览 • 1回复 待解决
HarmonyOS Web组件加载H5白屏
35浏览 • 1回复 待解决
HarmonyOS H5与应用侧数据交互Demo
594浏览 • 1回复 待解决
Web中webview和H5交互
1115浏览 • 1回复 待解决
HarmonyOS web原生和H5如何交互?
562浏览 • 1回复 待解决
HarmonyOS web通过loadData加载h5标签
270浏览 • 1回复 待解决
HarmonyOS Web组件加载本地H5文件跨域
31浏览 • 1回复 待解决
HarmonyOS H5调用APP图库选择图片
33浏览 • 1回复 待解决
HarmonyOS h5拉起系统扫码页面的demo
285浏览 • 1回复 待解决
HarmonyOS web上传文件图片
290浏览 • 1回复 待解决
HarmonyOS webH5两端数据交互
930浏览 • 1回复 待解决
HarmonyOS Web如何同H5进行交互传值
37浏览 • 1回复 待解决