Pārlūkot izejas kodu

多媒体采集可以和鸿蒙互通。

jiaxiaoqiang 9 mēneši atpakaļ
vecāks
revīzija
829f6fc091

+ 1 - 0
README.md

@@ -0,0 +1 @@
+1.更改url需要修改index.ets和JGRequest里面的

+ 0 - 175
entry/src/main/ets/pages/Base64Page.ets

@@ -1,175 +0,0 @@
-import common from '@ohos.app.ability.common';
-import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
-import bundleManager from '@ohos.bundle.bundleManager';
-import picker from '@ohos.file.picker';
-import fs from '@ohos.file.fs';
-import image from '@ohos.multimedia.image';
-import { BusinessError } from '@ohos.base';
-import fileUri from '@ohos.file.fileuri';
-import { FormData, File, FileUpload } from "@ohos/commons-fileupload"
-import http from '@ohos.net.http';
-
-@Entry
-@Component
-export struct MinePage {
-  @State profileSrc: Resource = $r('app.media.icon')
-  @State profileImage: PixelMap = new Object() as PixelMap
-  @State uri: string = ''
-  @State flag: number = 0
-
-  // 选择头像图片
-  // 定义一个函数用于点击头像时拉起用户图库
-  async pickProfile1() {
-    const photoSelectOptions = new picker.PhotoSelectOptions();
-    // 设置选择的文件类型为图片类型
-    photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
-    // 一次只能选择一张图片
-    photoSelectOptions.maxSelectNumber = 1;
-    let uri = "";
-    const photoViewPicker = new picker.PhotoViewPicker();
-    // 拉起图库,获取选中图片的uri
-    photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
-      // 获取选中图片的uri
-      uri = photoSelectResult.photoUris[0];
-      this.uri = uri
-      this.flag = 1
-      console.info('photoViewPicker.select to file succeed and uris are:' + uri)
-    }).catch((err: BusinessError) => {
-      console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
-    })
-    this.getPixelMap()
-  }
-
-  // 定义一个函数用于点击头像时拉起用户图库
-  async pickProfile() {
-    const photoSelectOptions = new picker.PhotoSelectOptions();
-    // 设置选择的文件类型为图片类型
-    photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
-    // 一次只能选择一张图片
-    photoSelectOptions.maxSelectNumber = 1;
-    const photoViewPicker = new picker.PhotoViewPicker();
-    // 拉起图库,获取选中图片的uri,并将选择图片拷贝至应用沙箱指定位置
-    photoViewPicker.select(photoSelectOptions)
-      .then((photoSelectResult: picker.PhotoSelectResult) => {
-        // 获取选中图片的uri
-        let imageUri = photoSelectResult.photoUris[0];
-        console.info('photoViewPicker.select to file succeed and uris are:' + imageUri);
-        let context = getContext(this)
-        //获取应用通用文件路径
-        let filesDir = context.filesDir
-        let fileName = "userProfileImage"
-        //获取沙箱中文件路径
-        let path = filesDir + "/" + fileName + "." + imageUri.split(".")[1]
-        let file = fs.openSync(imageUri, fs.OpenMode.READ_ONLY)
-        let file2 = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
-        //完成图片拷贝
-        fs.copyFileSync(file.fd, file2.fd)
-        fs.closeSync(file.fd)
-        fs.closeSync(file2.fd)
-        //获取图片沙箱路径对应的uri
-        this.uri = fileUri.getUriFromPath(path)
-        console.log("ddddddd this.url", this.uri)
-        //获取图片对应的PixelMap
-        this.getPixelMap()
-      })
-      .catch((err: BusinessError) => {
-        console.error('MinePage', `Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
-      })
-  }
-
-  // 获取图片的pixelmap
-  getPixelMap() {
-    // 通过uri打开图片文件,获取文件fd
-    let file = fs.openSync(this.uri, fs.OpenMode.READ_WRITE);
-    const imageSourceApi = image.createImageSource(file.fd);
-
-
-    try {
-      // 将图片解码为pixelmap
-      imageSourceApi.createPixelMap().then(pixelmap => {
-        this.profileImage = pixelmap
-        console.log('ddddddddd Succeeded in creating pixelmap object through image decoding parameters.');
-      }).catch((err: BusinessError) => {
-        console.log('ddddddddd Failed to create pixelmap object through image decoding parameters.');
-      })
-    }
-    catch (e) {
-      console.log('ddddddddd Failed')
-    }
-  }
-
-  private async openGallery() {
-    let context = getContext(this) as common.UIAbilityContext;
-    let atManager = abilityAccessCtrl.createAtManager();
-    let info = await bundleManager.getBundleInfoForSelf(0);
-    // if (info && info.appInfo) {
-    //   let result = atManager.verifyAccessTokenSync(info.appInfo.accessTokenId, "ohos.permission.READ_MEDIA");
-    //   if (abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED == result) {
-    //     console.log("has permission")
-    //   }
-    // } else {
-    atManager.requestPermissionsFromUser(context, ["ohos.permission.READ_MEDIA", "ohos.permission.WRITE_MEDIA"], (error, result) => {
-      if (result) {
-        console.log("result: " + JSON.stringify(result));
-        if (result.authResults[0] == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
-          // 用户授予权限
-          this.pickProfile1();
-        } else {
-          // 用户拒绝权限
-          console.log("permission denied")
-        }
-      } else {
-        console.log("error: " + JSON.stringify(error));
-      }
-    });
-    // }
-  }
-
-  aboutToAppear() {
-
-  }
-
-  build() {
-    Column() {
-      Image(this.profileImage)
-        .border({ width: 3, color: Color.Blue })
-        .width(108)
-        .height(108)
-        .objectFit(ImageFit.Cover)
-        .borderRadius(54)
-        .onClick(() => {
-          // this.openGallery()
-
-          let fileUpload = new FileUpload({
-            baseUrl: "http://10.88.11.200:8078",
-            readTimeout: 60000,
-            connectTimeout: 60000
-          })
-
-          // fileUpload.get({ url: "http://10.88.11.200:8078/api/v1/sys/dept/orgList" }).then((res: http.HttpResponse) => {
-          //   console.info("ddddddddd" + JSON.stringify(res));
-          // })
-
-          const formData = new FormData();
-          formData.append("key", 1); //可以添加基本类型的值,目前支持string、number
-          formData.append("myFile", "File"); //也可以添加File类型的对象
-
-
-          fileUpload.post("/api/v1/base/upload", formData).then(res => {
-            console.log("ddddddd success", JSON.stringify(res));
-          }).catch((err: BusinessError) => {
-            console.error("ddddddd    fail", JSON.stringify(err));
-          })
-        })
-      if (!this.uri) {
-        Text('点击上传头像')
-          .fontSize(24)
-          .margin({ top: 10 })
-      }
-    }
-    .alignItems(HorizontalAlign.Center)
-    .justifyContent(FlexAlign.Center)
-    .width('100%')
-    .height('100%')
-  }
-}

+ 1 - 0
entry/src/main/ets/pages/CameraPage.ets

@@ -43,6 +43,7 @@ struct Index {
     this.isUploading = true
     uploadInstance.startUpload(assetUri, () => {
       this.isUploading = false
+      this.assetUri = ""
       console.log(TAG, "上传完成后的callback")
     })
 

+ 17 - 196
entry/src/main/ets/pages/Index.ets

@@ -1,56 +1,16 @@
 import web_webview from '@ohos.web.webview';
 import process from '@ohos.process'
-import common from '@ohos.app.ability.common';
-import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
-import bundleManager from '@ohos.bundle.bundleManager';
-import picker from '@ohos.file.picker';
-import http from '@ohos.net.http';
-import { BusinessError } from '@ohos.base';
-import { FormData, File, FileUpload } from "@ohos/commons-fileupload"
-import fs from '@ohos.file.fs';
-import { ProgressDialog } from '../components/ProgressDialog';
 import router from '@ohos.router';
-import uploadInstance from '../utils/UploadUtil';
+import uploadInstance from "../utils/UploadUtil"
 
 
-interface DownStartModel {
-  url: string;
-  userAgent: string;
-  contentDisposition: string;
-  mimetype: string
-  contentLength: number
-}
-
-interface FileResponseModel {
-  code?: string
-  data?: string
-  msg?: string
-}
-
-interface BridgeParams {
-  path?: string
-  token?: string
-  method?: "get" | "post"
-  //   产线code。 id。
-  //   扫码开工的id
-  //   工序的id
-}
-
-interface FileSelectorEvent {
-  result: FileSelectorResult,
-  fileSelector: FileSelectorParam
-}
-
 const TAG = "openHarmonyBridge" //webview和vue沟通的名称
-const baseUrl = "http://10.88.11.200:10000"
-const proxyPrefix = "/mes-server"
+const webUrl = "http://10.88.11.200:11000"
 
+// const webUrl = "http://10.88.20.88:3005/"
 
 class BridgeModel {
-  context: common.UIAbilityContext
-
-  constructor(c: common.UIAbilityContext) {
-    this.context = c
+  constructor() {
   }
 
   // this.controller.registerJavaScriptProxy 这个里面要对应
@@ -59,19 +19,19 @@ class BridgeModel {
     // let downloadUrl: string = baseUrl + proxyPrefix + params.path
     // console.info(TAG, `download:`, downloadUrl);
     console.info(TAG, `params:`, params);
-
-    let p: BridgeParams = JSON.parse(params)
-
-
     // return true;
   }
 
   selectFile(params: string): void {
     console.info(TAG, `selectFile:`, params);
+    uploadInstance.configUploadParam(params)
+    router.pushUrl({ url: "pages/SelectFilePage" })
   }
 
   startCamera(params: string): void {
     console.info(TAG, `startCamera:`, params);
+    uploadInstance.configUploadParam(params)
+    router.pushUrl({ url: "pages/CameraPage" })
   }
 }
 
@@ -80,18 +40,8 @@ class BridgeModel {
 @Component
 struct Index {
   controller: web_webview.WebviewController = new web_webview.WebviewController();
-  @State mode: MixedMode = MixedMode.All
-  UIAbilityContext: common.UIAbilityContext = getContext(this) as common.UIAbilityContext
-  dialogController: CustomDialogController = new CustomDialogController({
-    builder: ProgressDialog({
-      // cancel: ()=> { this.onCancel() },
-      // confirm: ()=> { this.onAccept() },
-    }),
-    alignment: DialogAlignment.Center,
-    customStyle: true,
-  })
   // 声明需要注册的对象
-  @State bridgeObj: BridgeModel = new BridgeModel(this.UIAbilityContext);
+  @State bridgeObj: BridgeModel = new BridgeModel();
   hasRegistered: boolean = false
   registerJS = () => {
 
@@ -102,148 +52,19 @@ struct Index {
       this.controller.refresh()
       this.hasRegistered = true
     }
-
-
-  }
-
-  aboutToAppear(): void {
-    // this.hasRegistered = false
-    // setTimeout(() => {
-    //   this.registerJS()
-    // }, 2000)
-    // this.dialogController.open()
-
-  }
-
-  private async openGallery() {
-    let context = getContext(this) as common.UIAbilityContext;
-    let atManager = abilityAccessCtrl.createAtManager();
-    let info = await bundleManager.getBundleInfoForSelf(0);
-    if (info && info.appInfo) {
-      let result = atManager.verifyAccessTokenSync(info.appInfo.accessTokenId, "ohos.permission.READ_MEDIA");
-      if (abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED == result) {
-        console.log("has permission")
-      }
-    } else {
-      atManager.requestPermissionsFromUser(context, ["ohos.permission.READ_MEDIA"], (error, result) => {
-        if (result) {
-          console.log("result: " + JSON.stringify(result));
-          if (result.authResults[0] == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
-            // 用户授予权限
-            this.openGalleryInternal();
-          } else {
-            // 用户拒绝权限
-            console.log("permission denied")
-          }
-        } else {
-          console.log("error: " + JSON.stringify(error));
-        }
-      });
-    }
-  }
-
-  private openGalleryInternal() {
-    let photoPicker = new picker.PhotoViewPicker();
-    photoPicker.select({
-      MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
-      maxSelectNumber: 1
-    }, (error, result) => {
-      if (result) {
-
-        this.dialogController.open()
-
-        // this.uploadImage(result.photoUris); file://media/Photo/3/IMG_1723222627_002/IMG_20240810_005707.jpg
-        result.photoUris.forEach((url) => {
-          // console.log("uploadLog: 选择完图片的路径" + url);
-
-          uploadInstance.startUpload(url, () => {
-            this.dialogController.close()
-          })
-
-          // try {
-          //   const uri = url
-          //   // 2.2 根据uri同步打开文件
-          //   const file = fs.openSync(uri)
-          //   // 2.3 同步获取文件的详细信息
-          //   const stat = fs.statSync(file.fd)
-          //   // 2.4 创建缓冲区存储读取的文件流
-          //   const buffer = new ArrayBuffer(stat.size)
-          //   // 2.5 开始同步读取文件流到缓冲区
-          //   fs.readSync(file.fd, buffer)
-          //   // 2.6 关闭文件流
-          //   fs.closeSync(file)
-          //
-          //   // 3. 转成base64编码的字符串
-          //   // const helper = new util.Base64Helper()
-          //   // const str = helper.encodeToStringSync(new Uint8Array(buffer))
-          //   console.log('mk-logger', 'photoPlugin-str', buffer.byteLength, JSON.stringify(buffer))
-          //
-          //   let toUpFile = new File()
-          //   toUpFile.fileName = "test.jpg"
-          //   toUpFile.fileData = buffer
-          //
-          //   let fileUpload = new FileUpload({
-          //     baseUrl: "http://10.88.11.200:8078",
-          //     readTimeout: 60000,
-          //     connectTimeout: 60000,
-          //   })
-          //
-          //   const formData = new FormData();
-          //   // formData.append("key", 1); //可以添加基本类型的值,目前支持string、number
-          //   formData.append("fileName", "test.jpg"); //也可以添加File类型的对象
-          //   // formData.append('file', `internal://cache/${fileName}`)
-          //   formData.append('file', toUpFile)
-          //
-          //   fileUpload.post("/api/v1/base/upload", formData, {
-          //
-          //     header: {
-          //       'Content-Type': 'multipart/form-data',
-          //       'Authorization': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOnsiaWQiOjEwMDAwLCJ1c2VyTmFtZSI6ImFkbWluIiwiZGVwdElkIjoxLCJzdGF0aW9uSWQiOjAsImF2YXRhciI6Ii9qZ2ZpbGUvLzIwMjQvNS8yNy8yNzQzMjkzOTU4Mzg4NTIuanBnIiwib3JnSWQiOjF9LCJkZXZpY2UiOiJiYWNrIiwiZWZmIjoxNzIzOTQ2NTQwNzQxLCJyblN0ciI6InpkOWpKZFlBdVpnR0NEd2xBWnZIcXpkUThBaW9xaUh6In0.8fEZh6HCbkE0kmwF6Ru-1JtVSfQN39mB51pIsI6bzDI"
-          //     },
-          //   }).then((res: http.HttpResponse) => {
-          //     this.dialogController.close()
-          //     let model: FileResponseModel = res.result as FileResponseModel
-          //
-          //     // let data: FileModel = JSON.parse(model.data)
-          //
-          //     console.log(TAG, "ddddddd success", JSON.stringify(model));
-          //
-          //     // let data: ESObject = res.result as ESObject
-          //     // // this.netImageUrl = data.data.fileUrl ?? ""
-          //     // console.error("ddddddd    图片地址:  ", `http://10.88.11.201:9000/${data.data.fileUrl}`);
-          //   }).catch((err: BusinessError) => {
-          //     this.dialogController.close()
-          //     console.error(TAG, "ddddddd    fail");
-          //   })
-          // }
-          // catch (e) {
-          //   this.dialogController.close()
-          //   console.log(TAG, 'mk-logger', 'photoPlugin-str', JSON.stringify(e))
-          // }
-
-
-          // this.uploadImg3(url)
-          // this.uploadImg2(url)
-        })
-
-
-      }
-    });
   }
 
   build() {
     Column() {
       Stack() {
-        // Web({ src: $rawfile('download.html'), controller: this.controller })//测试下载proxy互相传值
-        // Web({ src: $rawfile('local.html'), controller: this.controller }) //测试webview里面选择文件
-        // Web({ src: $rawfile('camera.html'), controller: this.controller })//测试相机
-        Web({ src: $rawfile('doc_old.html'), controller: this.controller })//测试官方文档
+        // 这个webview调用相机不知道为什么只能执行一次,选择文件的回到还行,但是为了统一写法还是用registerJavaScriptProxy,但是有时候注册的方法也只能执行一次,不知道为什么。
+        // Web({ src: $rawfile('doc_old.html'), controller: this.controller })//测试官方文档 这个是好使的
 
-          // Web({
-          //   src: 'http://10.88.20.88:3005/login',
-          //   controller: this.controller
-          // })
-          .mixedMode(this.mode)
+        Web({
+          src: webUrl,
+          controller: this.controller
+        })
+          .mixedMode(MixedMode.All)
           .onlineImageAccess(true)
           .javaScriptAccess(true)
           .overviewModeAccess(true)
@@ -251,7 +72,7 @@ struct Index {
           .domStorageAccess(true)
           .onShowFileSelector((event) => {
             console.log(TAG, "onShowFileSelector", JSON.stringify(event))
-            this.openGallery()
+            // this.openGallery()
             // setTimeout(() => {
             //   // 这个会触发addEventListener('change')的事件,但是每次的值都要不同。
             //   event?.result.handleFileList([Date.now() + '.jpg']);

+ 0 - 395
entry/src/main/ets/pages/SelectAlbumPage.ets

@@ -1,395 +0,0 @@
-import common from '@ohos.app.ability.common';
-import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
-import bundleManager from '@ohos.bundle.bundleManager';
-import picker from '@ohos.file.picker';
-import request from '@ohos.request';
-import http from '@ohos.net.http';
-import fs from '@ohos.file.fs';
-import { BusinessError } from '@ohos.base';
-
-import axios, { AxiosError, AxiosProgressEvent, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios'
-import JGRequest from '../utils/Request';
-
-import { FormData, File, FileUpload } from "@ohos/commons-fileupload"
-
-const logTag = "uploadLog"
-
-
-interface FileResponseModel {
-  code?: string
-  data?: string
-  msg?: string
-}
-
-interface FileModel {
-  fileUrl?: string
-  fileName?: string
-}
-
-
-@Entry
-@Component
-struct Index {
-  @State html: string = "权限状态未知";
-  @State netImageUrl: string = ""
-
-  build() {
-    Column({ space: 10 }) {
-
-      Button("请求权限")
-        .onClick(() => {
-
-          // axios.get("http://10.88.11.200:8078/api/v1/sys/dept/orgList").then((res: AxiosResponse) => {
-          //   console.info(logTag, "测试" + JSON.stringify(res.data));
-          // })
-          //
-          // let formData = new FormData()
-          // let cacheDir = getContext(this).cacheDir
-          //
-          // let path = cacheDir + '/hello.txt';
-          // let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
-          // fs.writeSync(file.fd, "hello, world"); // 以同步方法将数据写入文件
-          // fs.fsyncSync(file.fd); // 以同步方法同步文件数据。
-          // fs.closeSync(file.fd);
-          //
-          //
-          // // formData.append('file', 'internal://cache/blue.jpg')
-          // // formData.append('file', cacheDir + '/hello.txt'); // uri支持传入沙箱路径
-          // formData.append("fdd", "dddd")
-          //
-          // // 发送请求
-          // axios.post<string, AxiosResponse<string>, FormData>('http://10.88.11.200:8078/api/v1/base/upload', formData, {
-          //   headers: {
-          //     'Content-Type': 'multipart/form-data',
-          //     'Authorization': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOnsiaWQiOjEwMDAwLCJ1c2VyTmFtZSI6ImFkbWluIiwiZGVwdElkIjoxLCJzdGF0aW9uSWQiOjAsImF2YXRhciI6Ii9qZ2ZpbGUvLzIwMjQvNS8yNy8yNzQzMjkzOTU4Mzg4NTIuanBnIiwib3JnSWQiOjF9LCJkZXZpY2UiOiJiYWNrIiwiZWZmIjoxNzIzOTQ2NTQwNzQxLCJyblN0ciI6InpkOWpKZFlBdVpnR0NEd2xBWnZIcXpkUThBaW9xaUh6In0.8fEZh6HCbkE0kmwF6Ru-1JtVSfQN39mB51pIsI6bzDI"
-          //   },
-          //   context: getContext(this),
-          //   onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
-          //     console.info(progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%');
-          //   },
-          // }).then((res: AxiosResponse<string>) => {
-          //   console.info(logTag, "result" + JSON.stringify(res.data));
-          // }).catch((err: AxiosError) => {
-          //   console.error(logTag, "error:" + JSON.stringify(err));
-          // })
-
-
-          // JGRequest.get("/api/v1/sys/dept/orgList")
-          // JGRequest.post("/api/v1/device/config/addBatch")
-          this.openGallery();
-          // JGRequest.post("api/v1/base/upload") // printResponse data {"code":"4106","data":null,"msg":"当前用户未登录或登录已失效"}
-        })
-      Text(this.html)
-    }
-    .width('100%')
-    .height('100%')
-    .padding(10)
-  }
-
-  private async openGallery() {
-    let context = getContext(this) as common.UIAbilityContext;
-    let atManager = abilityAccessCtrl.createAtManager();
-    let info = await bundleManager.getBundleInfoForSelf(0);
-    if (info && info.appInfo) {
-      let result = atManager.verifyAccessTokenSync(info.appInfo.accessTokenId, "ohos.permission.READ_MEDIA");
-      if (abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED == result) {
-        console.log("has permission")
-      }
-    } else {
-      atManager.requestPermissionsFromUser(context, ["ohos.permission.READ_MEDIA"], (error, result) => {
-        if (result) {
-          console.log("result: " + JSON.stringify(result));
-          if (result.authResults[0] == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
-            // 用户授予权限
-            this.html = "用户已经授权";
-            this.openGalleryInternal();
-          } else {
-            // 用户拒绝权限
-            this.html = "用户拒绝授权";
-            console.log("permission denied")
-          }
-        } else {
-          this.html = "请求授权异常:" + JSON.stringify(error);
-          console.log("error: " + JSON.stringify(error));
-        }
-      });
-    }
-  }
-
-  private openGalleryInternal() {
-    let photoPicker = new picker.PhotoViewPicker();
-    photoPicker.select({
-      MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
-      maxSelectNumber: 1
-    }, (error, result) => {
-      if (result) {
-        // this.uploadImage(result.photoUris); file://media/Photo/3/IMG_1723222627_002/IMG_20240810_005707.jpg
-        result.photoUris.forEach((url) => {
-          console.log("uploadLog: 选择完图片的路径" + url);
-
-          try {
-            const uri = url
-            // 2.2 根据uri同步打开文件
-            const file = fs.openSync(uri)
-            // 2.3 同步获取文件的详细信息
-            const stat = fs.statSync(file.fd)
-            // 2.4 创建缓冲区存储读取的文件流
-            const buffer = new ArrayBuffer(stat.size)
-            // 2.5 开始同步读取文件流到缓冲区
-            fs.readSync(file.fd, buffer)
-            // 2.6 关闭文件流
-            fs.closeSync(file)
-
-            // 3. 转成base64编码的字符串
-            // const helper = new util.Base64Helper()
-            // const str = helper.encodeToStringSync(new Uint8Array(buffer))
-            console.log('mk-logger', 'photoPlugin-str', buffer.byteLength, JSON.stringify(buffer))
-
-            let toUpFile = new File()
-            toUpFile.fileName = "test.jpg"
-            toUpFile.fileData = buffer
-
-            let fileUpload = new FileUpload({
-              baseUrl: "http://10.88.11.200:8078",
-              readTimeout: 60000,
-              connectTimeout: 60000,
-            })
-
-            const formData = new FormData();
-            // formData.append("key", 1); //可以添加基本类型的值,目前支持string、number
-            formData.append("fileName", "test.jpg"); //也可以添加File类型的对象
-            // formData.append('file', `internal://cache/${fileName}`)
-            formData.append('file', toUpFile)
-
-            fileUpload.post("/api/v1/base/upload", formData, {
-
-              header: {
-                'Content-Type': 'multipart/form-data',
-                'Authorization': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOnsiaWQiOjEwMDAwLCJ1c2VyTmFtZSI6ImFkbWluIiwiZGVwdElkIjoxLCJzdGF0aW9uSWQiOjAsImF2YXRhciI6Ii9qZ2ZpbGUvLzIwMjQvNS8yNy8yNzQzMjkzOTU4Mzg4NTIuanBnIiwib3JnSWQiOjF9LCJkZXZpY2UiOiJiYWNrIiwiZWZmIjoxNzIzOTQ2NTQwNzQxLCJyblN0ciI6InpkOWpKZFlBdVpnR0NEd2xBWnZIcXpkUThBaW9xaUh6In0.8fEZh6HCbkE0kmwF6Ru-1JtVSfQN39mB51pIsI6bzDI"
-              },
-            }).then((res: http.HttpResponse) => {
-              let model: FileResponseModel = res.result as FileResponseModel
-
-              // let data: FileModel = JSON.parse(model.data)
-
-              console.log("ddddddd success", JSON.stringify(model));
-
-              // let data: ESObject = res.result as ESObject
-              // // this.netImageUrl = data.data.fileUrl ?? ""
-              // console.error("ddddddd    图片地址:  ", `http://10.88.11.201:9000/${data.data.fileUrl}`);
-            }).catch((err: BusinessError) => {
-              console.error("ddddddd    fail");
-            })
-          }
-          catch (e) {
-            console.log('mk-logger', 'photoPlugin-str', JSON.stringify(e))
-          }
-
-
-          // this.uploadImg3(url)
-          // this.uploadImg2(url)
-        })
-      }
-    });
-  }
-
-  //fileUri是文件选择器返回的路径,格式如下: "datashare:///media/image/45"
-
-  async uploadImg3(fileUri: string) {
-    //      uploadLog: file://media/Photo/2/IMG_1723222626_001/IMG_20240810_005706.jpg
-    //   uploadLog cacheDir /data/storage/el2/base/haps/entry/cache
-    // uploadLog error:{"message":"NetWork is offline","name":"AxiosError","stack":"
-
-    // / 获取应用文件路径
-    const context = getContext(this) as common.UIAbilityContext;
-    let cacheDir = context.cacheDir;
-    console.log(logTag, 'cacheDir', cacheDir);
-    //=>沙箱路径 /应用文件目录 /data/storage/el2/base/haps/entry/cache
-
-    //文件名称,下面这两种方法都可以,原则就是保持名字随机性
-    // let segments = fileUri.split('/')
-    // let fileName = segments[segments.length-1]
-    const fileName = Date.now() + '.jpg'
-    //复制这一步一定不能少 ,简而言之,就是把我们的内部文件拿到外部暴露出来,
-    let realUri = context.cacheDir + "/" + fileName //计划复制到的目标路径
-    try {
-      let file = fs.openSync(fileUri);
-      fs.copyFileSync(file.fd, realUri)
-    } catch (err) {
-      console.info(logTag, 'err:' + JSON.stringify(err));
-    }
-
-
-    // let formData = new FormData()
-    // formData.append('file', `internal://cache/${fileName}`)
-    //
-    // // 发送请求
-    // axios.post<string, AxiosResponse<string>, FormData>('http://10.88.11.200:8078/api/v1/base/upload', formData, {
-    //   headers: { 'Content-Type': 'multipart/form-data' },
-    //   context: getContext(this),
-    //   onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
-    //     console.info(progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%');
-    //   },
-    // }).then((res: AxiosResponse<string>) => {
-    //   console.info("uploadLog" + JSON.stringify(res.data));
-    // }).catch((err: AxiosError) => {
-    //   console.error("uploadLog:" + JSON.stringify(err));
-    // })
-
-
-    // try {
-    //
-    //   // 第三方库axios请求
-    //   let formData = new FormData();
-    //   formData.append('file', `internal://cache/${fileName}`, fileName);
-    //   // formData.append('fileName', fileName);
-    //   // console.info(logTag, "formData", JSON.stringify(formData));
-    //   //记得替换真实请求地址
-    //   // JGRequest.post()
-    //   JGRequest.post<string, AxiosResponse<string>, FormData>("/api/v1/base/upload", formData, {
-    //     // axios.post<string, AxiosResponse<string>, FormData>("http://10.88.11.200:8078/api/v1/base/upload", formData, {
-    //     headers: {
-    //       'Content-Type': 'multipart/form-data',
-    //       'Authorization': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOnsiaWQiOjEwMDAwLCJ1c2VyTmFtZSI6ImFkbWluIiwiZGVwdElkIjoxLCJzdGF0aW9uSWQiOjAsImF2YXRhciI6Ii9qZ2ZpbGUvLzIwMjQvNS8yNy8yNzQzMjkzOTU4Mzg4NTIuanBnIiwib3JnSWQiOjF9LCJkZXZpY2UiOiJiYWNrIiwiZWZmIjoxNzIzOTQ2NTQwNzQxLCJyblN0ciI6InpkOWpKZFlBdVpnR0NEd2xBWnZIcXpkUThBaW9xaUh6In0.8fEZh6HCbkE0kmwF6Ru-1JtVSfQN39mB51pIsI6bzDI"
-    //     },
-    //     context: getContext(this),
-    //     onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
-    //       console.info(logTag, progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%');
-    //     },
-    //   }).then((res: AxiosResponse) => {
-    //     interface pathType {
-    //       filePath: string
-    //     }
-    //
-    //     interface dataType {
-    //       data: pathType
-    //     }
-    //
-    //     const data: dataType = res.data as dataType
-    //     const path = data.data.filePath
-    //     console.info(logTag, "request result", path);
-    //   }).catch((error: AxiosError) => {
-    //     console.error(logTag, "11111error:" + JSON.stringify(error));
-    //   })
-    // } catch (err) {
-    //   console.error(logTag, `axios Failed to request the upload. err: ${JSON.stringify(err)}`);
-    // }
-
-
-  }
-
-  // async uploadImg2(fileUri: string) {
-  //   // uploadLog Failed to request the upload. Code: undefined, message: Cannot read property on of undefined
-  //   // / 获取应用文件路径
-  //   const context = getContext(this) as common.UIAbilityContext;
-  //   let cacheDir = context.cacheDir;
-  //   console.log(logTag, 'cacheDir', cacheDir);
-  //   //=>沙箱路径 /应用文件目录 /data/storage/el2/base/haps/entry/cache
-  //
-  //   //文件名称,下面这两种方法都可以,原则就是保持名字随机性
-  //   // let segments = fileUri.split('/')
-  //   // let fileName = segments[segments.length-1]
-  //   const fileName = Date.now() + '.jpg'
-  //   //复制这一步一定不能少 ,简而言之,就是把我们的内部文件拿到外部暴露出来,
-  //   let realUri = context.cacheDir + "/" + fileName //计划复制到的目标路径
-  //   try {
-  //     let file = fs.openSync(fileUri);
-  //     fs.copyFileSync(file.fd, realUri)
-  //   } catch (err) {
-  //     console.info(logTag, 'err:' + JSON.stringify(err));
-  //   }
-  //
-  //
-  //   // // 鸿蒙自带请求
-  //   let uploadTask: request.UploadTask;
-  //   let uploadConfig: request.UploadConfig = {
-  //     url: "http://10.88.11.200:8078/api/v1/base/upload", //需要手动替换为真实服务器地址
-  //     header: { 'Content-Type': 'multipart/form-data' },
-  //     method: "POST",
-  //     files: [{ filename: fileName, name: "file", uri: `internal://cache/${fileName}`, type: "jpg" }],
-  //     //注意这里,files里面的url一定是'internal://cache/'和文件名的拼接,不要拼其他路径!!!
-  //     data: [],
-  //   };
-  //   //一定要定义类型,这里的类型定义真的很让人头大
-  //   interface path {
-  //     filePath: string
-  //   }
-  //
-  //   interface bodyType {
-  //     code: string
-  //     success: string
-  //     data: path
-  //   }
-  //
-  //   interface resType {
-  //     body: bodyType
-  //   }
-  //
-  //   try {
-  //     request.uploadFile(context, uploadConfig).then((data: request.UploadTask) => {
-  //       uploadTask.on('headerReceive', (header: object) => {
-  //         const picRes: resType = header as resType
-  //         console.log(logTag, '上传头picRes', picRes.body)
-  //       })
-  //       uploadTask.on("complete", () => {
-  //         // promptAction.showToast({ message: '上传成功!', duration: 2000 })
-  //         // 上传成功调接口
-  //       })
-  //     }).catch((err: BusinessError) => {
-  //       console.error(logTag, `Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
-  //     });
-  //   } catch (err) {
-  //     console.error(logTag, ` err: ${JSON.stringify(err)}`);
-  //   }
-  //
-  // }
-
-  // private uploadImage(paths: string[]) {
-  //   let allFiles = Array<request.File>()
-  //
-  //   for (let i = 0; i < paths.length; i++) {
-  //     let path = paths[i]
-  //     console.log(logTag, "path: " + path)
-  //     allFiles[i] = {
-  //       name: "image" + i + ".jpg",
-  //       filename: "image" + i + ".jpg",
-  //       uri: path,
-  //       type: "image"
-  //     }
-  //   }
-  //
-  //
-  //   try {
-  //
-  //     request.uploadFile(getContext(this), {
-  //       url: "http://10.88.20.188:8079/api/v1/base/upload",
-  //       method: http.RequestMethod.POST,
-  //       files: allFiles,
-  //       header: {
-  //         'Content-Type': 'multipart/form-data',
-  //       },
-  //       data: [
-  //         {
-  //           name: "file",
-  //           value: "file"
-  //         }
-  //       ]
-  //     }, (error, response) => {
-  //       console.log(logTag, "response", JSON.stringify(error), JSON.stringify(response))
-  //       if (response) {
-  //         response.on('progress', (uploadedSize: number, totalSize: number) => {
-  //           console.log(logTag, "progress, uploadedSize: " + uploadedSize + ", totalSize: " + totalSize)
-  //         })
-  //       } else {
-  //         console.log(logTag, "upload failure: " + error)
-  //       }
-  //     });
-  //
-  //   } catch (err) {
-  //     console.error(logTag, `xx Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
-  //
-  //   }
-  //
-  //
-  // }
-}

+ 110 - 0
entry/src/main/ets/pages/SelectFilePage.ets

@@ -0,0 +1,110 @@
+import web_webview from '@ohos.web.webview';
+import process from '@ohos.process'
+import common from '@ohos.app.ability.common';
+import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
+import bundleManager from '@ohos.bundle.bundleManager';
+import picker from '@ohos.file.picker';
+import http from '@ohos.net.http';
+import { BusinessError } from '@ohos.base';
+import { FormData, File, FileUpload } from "@ohos/commons-fileupload"
+import fs from '@ohos.file.fs';
+import { ProgressDialog } from '../components/ProgressDialog';
+import router from '@ohos.router';
+import uploadInstance from '../utils/UploadUtil';
+import { GlobalContext } from '../utils/GlobalThis';
+
+
+@Entry
+@Component
+struct Index {
+  UIAbilityContext: common.UIAbilityContext = getContext(this) as common.UIAbilityContext
+  dialogController: CustomDialogController = new CustomDialogController({
+    builder: ProgressDialog({
+      // cancel: ()=> { this.onCancel() },
+      // confirm: ()=> { this.onAccept() },
+    }),
+    alignment: DialogAlignment.Center,
+    customStyle: true,
+  })
+
+  aboutToAppear(): void {
+    this.openGallery()
+  }
+
+  private async openGallery() {
+
+    let atManager = abilityAccessCtrl.createAtManager();
+    let info = await bundleManager.getBundleInfoForSelf(0);
+    if (info && info.appInfo) {
+      let result = atManager.verifyAccessTokenSync(info.appInfo.accessTokenId, "ohos.permission.READ_MEDIA");
+      if (abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED == result) {
+        console.log("has permission")
+      }
+    } else {
+      atManager.requestPermissionsFromUser(this.UIAbilityContext, ["ohos.permission.READ_MEDIA"], (error, result) => {
+        if (result) {
+          console.log("result: " + JSON.stringify(result));
+          if (result.authResults[0] == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
+            // 用户授予权限
+            this.openGalleryInternal();
+          } else {
+            // 用户拒绝权限
+            console.log("permission denied")
+          }
+        } else {
+          console.log("error: " + JSON.stringify(error));
+        }
+      });
+    }
+  }
+
+  private openGalleryInternal() {
+    let photoPicker = new picker.PhotoViewPicker();
+    photoPicker.select({
+      MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
+      maxSelectNumber: 1
+    }, (error, result) => {
+      if (result.photoUris && result.photoUris.length > 0) {
+        let totalCount = result.photoUris.length
+        let completeCount = 0
+        this.dialogController.open()
+        // this.uploadImage(result.photoUris); file://media/Photo/3/IMG_1723222627_002/IMG_20240810_005707.jpg
+        result.photoUris.forEach((url) => {
+          // console.log("uploadLog: 选择完图片的路径" + url);
+          uploadInstance.startUpload(url, () => {
+            completeCount = completeCount + 1
+            if (completeCount >= totalCount) {
+              this.dialogController.close()
+              router.back()
+            }
+          })
+        })
+      }
+    });
+  }
+
+  build() {
+    Column() {
+
+      Row() {
+        Image($r("app.media.back_white")).width(20).height(20)
+        Text("返回").fontColor(Color.White).fontSize(20).margin({ left: 5 })
+
+        Text("再次选择").fontColor(Color.White).fontSize(20).margin({ left: 20 })
+          .onClick(() => {
+            this.openGallery()
+          })
+      }
+      .align(Alignment.Start)
+      .position({ x: 10, y: 10 })
+      .onClick(() => {
+        router.back()
+      })
+
+    }
+    .width('100%')
+    .height('100%')
+    .backgroundColor($r("app.color.gray_bg"))
+
+  }
+}

+ 0 - 45
entry/src/main/ets/pages/TooSimplePage.ets

@@ -1,45 +0,0 @@
-// xxx.ets
-import web_webview from '@ohos.web.webview';
-import abilityAccessCtrl, { PermissionRequestResult, Permissions } from '@ohos.abilityAccessCtrl';
-
-@Entry
-@Component
-struct WebComponent {
-  controller: web_webview.WebviewController = new web_webview.WebviewController()
-
-  aboutToAppear() {
-    // 配置Web开启调试模式
-    web_webview.WebviewController.setWebDebuggingAccess(true);
-    let atManager = abilityAccessCtrl.createAtManager();
-    atManager.requestPermissionsFromUser(getContext(this), ['ohos.permission.CAMERA', 'ohos.permission.MICROPHONE'])
-      .then(data => {
-        let result: Array<number> = data.authResults;
-        let hasPermissions1 = true;
-        result.forEach(item => {
-          if (item === -1) {
-            hasPermissions1 = false;
-          }
-        })
-        if (hasPermissions1) {
-          console.info("hasPermissions1")
-        } else {
-          console.info(" not hasPermissions1")
-        }
-      }).catch(() => {
-      return;
-    });
-  }
-
-  build() {
-    Column() {
-      Web({ src: $rawfile('camera.html'), controller: this.controller })
-        .onPermissionRequest((event) => {
-          if (event) {
-            console.log("openHarmonyBridge", "onPermissionRequest")
-            event.request.grant(event.request.getAccessibleResource())
-          }
-          return true
-        })
-    }
-  }
-}

+ 0 - 61
entry/src/main/ets/pages/WebTestPage.ets

@@ -1,61 +0,0 @@
-// xxx.ets
-import web_webview from '@ohos.web.webview';
-import abilityAccessCtrl, { PermissionRequestResult, Permissions } from '@ohos.abilityAccessCtrl';
-
-@Entry
-@Component
-struct WebComponent {
-  controller: web_webview.WebviewController = new web_webview.WebviewController()
-
-  aboutToAppear() {
-    // 配置Web开启调试模式
-    web_webview.WebviewController.setWebDebuggingAccess(true);
-    let atManager = abilityAccessCtrl.createAtManager();
-    atManager.requestPermissionsFromUser(getContext(this), ['ohos.permission.CAMERA', 'ohos.permission.MICROPHONE'])
-      .then(data => {
-        let result: Array<number> = data.authResults;
-        let hasPermissions1 = true;
-        result.forEach(item => {
-          if (item === -1) {
-            hasPermissions1 = false;
-          }
-        })
-        if (hasPermissions1) {
-          console.info("hasPermissions1")
-        } else {
-          console.info(" not hasPermissions1")
-        }
-      }).catch(() => {
-      return;
-    });
-  }
-
-  build() {
-    Column() {
-      Web({ src: $rawfile('camera.html'), controller: this.controller })
-        .onPermissionRequest((event) => {
-          if (event) {
-            AlertDialog.show({
-              title: 'title',
-              message: 'text',
-              primaryButton: {
-                value: 'deny',
-                action: () => {
-                  event.request.deny()
-                }
-              },
-              secondaryButton: {
-                value: 'onConfirm',
-                action: () => {
-                  event.request.grant(event.request.getAccessibleResource())
-                }
-              },
-              cancel: () => {
-                event.request.deny()
-              }
-            })
-          }
-        })
-    }
-  }
-}

+ 5 - 5
entry/src/main/ets/utils/Request.ets

@@ -10,15 +10,16 @@ import axios, {
 //import PreferencesUtil from '../PreferencesUtil';
 import { printError, printRequest, printResponse, handleRes } from './Helps';
 import RequestParamsModel from './requestParams';
+import uploadInstance from './UploadUtil';
+
+export  const JGRequestBaseUrl = "http://10.88.11.200:8079/"
 
-// const baseUrl = "http://10.88.20.188:8079/"
-const baseUrl = "http://10.88.11.200:8078/"
 const DEBUG = true //
 
 // 创建实例
 const JGRequest = axios.create(
   {
-    baseURL: baseUrl,
+    baseURL: JGRequestBaseUrl,
     headers: {
       'Content-Type': 'application/json;charset=UTF-8',
     },
@@ -30,8 +31,7 @@ const JGRequest = axios.create(
 JGRequest.interceptors.request.use((config: InternalAxiosRequestConfig) => {
 
   // 以后登录之后可以在这里传
-  // config.headers.Authorization = ""
-  config.headers.Authorization = ""
+  config.headers.Authorization = uploadInstance?.uploadParams?.token ?? ""
   printRequest(config)
 
   return config;

+ 64 - 7
entry/src/main/ets/utils/UploadUtil.ets

@@ -3,18 +3,48 @@ import http from '@ohos.net.http'
 import { FormData, File, FileUpload } from "@ohos/commons-fileupload"
 import fs from '@ohos.file.fs';
 import { ProgressDialog } from '../components/ProgressDialog';
+import JGRequest, { JGRequestBaseUrl } from './Request';
 
 const TAG = "openHarmonyBridge upload"
 
 
+// 从webview那边穿过来的 用于上传完成后调接口的值
+interface BridgeParams {
+  token?: string,
+  operationMediaId?: string,
+  processId?: string,
+  seqNo?: string,
+  methodName?: string,
+  apiUrlPath?: string //上传完成后调的接口 不包含baseurl
+  method?: string
+}
+
+// 上传文件后,返回一个图片的url,然后再调用其他接口上传url和一些值, 如果有其他接口需要key,在这里添加,然后在下面赋值就行了
+interface APIParamsModel extends BridgeParams {
+  filePath?: string, //工序的多媒体采集需要用到的key
+}
+
+interface ResultModel {
+  code?: string
+  data?: FileDataModel
+  msg?: string
+}
+
+interface FileDataModel {
+  fileUrl?: string
+}
+
+
 class UploadUtil {
-  private uploadUrl: string = "http://10.88.11.200:8078"
+  private baseUrl: string = JGRequestBaseUrl
+  private uploadPath: string = "/api/v1/base/upload"
 
   private constructor() {
   }
 
-  public token: string = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOnsiaWQiOjEwMDAwLCJ1c2VyTmFtZSI6ImFkbWluIiwiZGVwdElkIjoxLCJzdGF0aW9uSWQiOjAsImF2YXRhciI6Ii9qZ2ZpbGUvLzIwMjQvNS8yNy8yNzQzMjkzOTU4Mzg4NTIuanBnIiwib3JnSWQiOjF9LCJkZXZpY2UiOiJiYWNrIiwiZWZmIjoxNzI0MTIyNTQwMTQwLCJyblN0ciI6IkRkakc3akFSNEtkZ1h5VWV5emhROFVib1ZlOTJUVVo4In0.yVzW8YkjiqLf9T4oUsJUPUifqPFANWX78pov8aGRsFQ"
-  private static instance: UploadUtil;
+  public uploadParams: BridgeParams = {}
+  // public token: string = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOnsiaWQiOjEwMDAwLCJ1c2VyTmFtZSI6ImFkbWluIiwiZGVwdElkIjoxLCJzdGF0aW9uSWQiOjAsImF2YXRhciI6Ii9qZ2ZpbGUvLzIwMjQvNS8yNy8yNzQzMjkzOTU4Mzg4NTIuanBnIiwib3JnSWQiOjF9LCJkZXZpY2UiOiJiYWNrIiwiZWZmIjoxNzI0MTIyNTQwMTQwLCJyblN0ciI6IkRkakc3akFSNEtkZ1h5VWV5emhROFVib1ZlOTJUVVo4In0.yVzW8YkjiqLf9T4oUsJUPUifqPFANWX78pov8aGRsFQ"
+  private static instance: UploadUtil; //单例实例
 
   public static getInstance(): UploadUtil {
     if (!UploadUtil.instance) {
@@ -23,7 +53,13 @@ class UploadUtil {
     return UploadUtil.instance;
   }
 
+  public configUploadParam(p: string) {
+    let model: BridgeParams = JSON.parse(p)
+    this.uploadParams = model
+  }
+
   startUpload(uri: string, callBack: () => void) {
+    // console.log(TAG, "token", this.token === this.uploadParams)
     //   开始上传
     try {
       // 2.2 根据uri同步打开文件
@@ -47,7 +83,7 @@ class UploadUtil {
       toUpFile.fileData = buffer
 
       let fileUpload = new FileUpload({
-        baseUrl: this.uploadUrl,
+        baseUrl: this.baseUrl,
         readTimeout: 60000,
         connectTimeout: 60000,
       })
@@ -56,14 +92,35 @@ class UploadUtil {
       // formData.append("key", 1); //可以添加基本类型的值,目前支持string、number
       // formData.append("fileName", "test.jpg"); //也可以添加File类型的对象
       formData.append('file', toUpFile)
-      fileUpload.post("/api/v1/base/upload", formData, {
+      fileUpload.post(this.uploadPath, formData, {
         header: {
           'Content-Type': 'multipart/form-data',
-          'Authorization': this.token,
+          // "Authorization": this.token
+          'Authorization': this.uploadParams?.token ?? "",
         },
       }).then((res: http.HttpResponse) => {
+
+        let result: ResultModel = JSON.parse(res.result as string)
+        console.log(TAG, "ddddddd success", JSON.stringify(result?.data ?? ""));
+
+
+        // 上传完成后调其他接口
+        if (this.uploadParams.apiUrlPath) {
+          let data: APIParamsModel = {
+            filePath: result.data?.fileUrl ?? "",
+            operationMediaId: this.uploadParams?.operationMediaId ?? "",
+            processId: this.uploadParams?.processId ?? "",
+            seqNo: this.uploadParams?.seqNo ?? "",
+          }
+
+          JGRequest.request({
+            method: this.uploadParams?.method ?? "post",
+            url: this.uploadParams?.apiUrlPath,
+            data: data
+          })
+        }
         callBack()
-        console.log(TAG, "ddddddd success", JSON.stringify(res.result));
+
         //上传完成后浏览器可以产看的图片地址  http://10.88.11.201:9000
       }).catch((err: BusinessError) => {
         callBack()

+ 10 - 8
entry/src/main/ets/utils/helps.ets

@@ -11,6 +11,8 @@ const pResponse = true
 const pData = true
 const pError = true
 
+const TAG = "openHarmonyBridge" //webview和vue沟通的名称
+
 // @CustomDialog
 // struct CustomDialogExample {
 //   controller: CustomDialogController
@@ -25,39 +27,39 @@ const pError = true
 
 const printRequest = (config: InternalAxiosRequestConfig) => {
   if (pConfig) {
-    console.debug("printRequest config", JSON.stringify(config))
+    console.debug(TAG, "printRequest config", JSON.stringify(config))
   }
 
   if (pHeaders) {
-    console.debug("printRequest headers", JSON.stringify(config.headers))
+    console.debug(TAG, "printRequest headers", JSON.stringify(config.headers))
   }
 
   if (pUrl) {
-    console.debug("printRequest url", `Method:${config.method} ${config.baseURL}${config.url}`)
+    console.debug(TAG, "printRequest url", `Method:${config.method} ${config.baseURL}${config.url}`)
   }
 
   if (pBody) {
-    console.debug("printRequest 请求参数data", JSON.stringify(config.data))
+    console.debug(TAG, "printRequest 请求参数data", JSON.stringify(config.data))
   }
 
   if (pParams) {
-    console.debug("printRequest 请求参数params", JSON.stringify(config.params))
+    console.debug(TAG, "printRequest 请求参数params", JSON.stringify(config.params))
   }
 
 }
 
 const printResponse = (response: AxiosResponse) => {
   if (pResponse) {
-    console.debug('handleRes response: ', JSON.stringify(response))
+    console.debug(TAG, 'handleRes response: ', JSON.stringify(response))
   }
   if (pData) {
-    console.debug("printResponse data", JSON.stringify(response.data))
+    console.debug(TAG, "printResponse data", JSON.stringify(response.data))
   }
 }
 
 const printError = (error: AxiosError) => {
   if (pError) {
-    console.debug("printError error", error.message)
+    console.debug(TAG, "printError error", error.message)
   }
   promptAction.showToast({
     message: error.message ?? "请求出错",

+ 4 - 0
entry/src/main/resources/base/element/color.json

@@ -3,6 +3,10 @@
     {
       "name": "start_window_background",
       "value": "#FFFFFF"
+    },
+    {
+      "name": "gray_bg",
+      "value": "#FF928888"
     }
   ]
 }

+ 2 - 4
entry/src/main/resources/base/profile/main_pages.json

@@ -1,9 +1,7 @@
 {
   "src": [
     "pages/Index",
-    "pages/WebTestPage",
-    "pages/SelectAlbumPage",
-    "pages/TooSimplePage",
-    "pages/CameraPage"
+    "pages/CameraPage",
+    "pages/SelectFilePage"
   ]
 }

+ 0 - 32
entry/src/main/resources/rawfile/camera.html

@@ -1,32 +0,0 @@
-<!-- index.html -->
-<!DOCTYPE html>
-<html>
-<head>
-    <meta charset="UTF-8">
-</head>
-<body>
-<video id="video" width="500px" height="500px" autoplay="autoplay"></video>
-<canvas id="canvas" width="500px" height="500px"></canvas>
-<br>
-<input type="button" title="HTML5摄像头" value="开启摄像头" onclick="getMedia()"/>
-<script>
-  function getMedia()
-  {
-    let constraints = {
-      video: {width: 500, height: 500},
-      audio: true
-    };
-    // 获取video摄像头区域
-    let video = document.getElementById("video");
-    // 返回的Promise对象
-    let promise = navigator.mediaDevices.getUserMedia(constraints);
-    // then()异步,调用MediaStream对象作为参数
-    promise.then(function (MediaStream) {
-      video.srcObject = MediaStream;
-      video.play();
-    });
-  }
-
-</script>
-</body>
-</html>

+ 0 - 75
entry/src/main/resources/rawfile/doc.html

@@ -1,75 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
-    <meta charset="UTF-8">
-    <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <title>File Input Example</title>
-</head>
-<body>
-<input type="file" id="fileInput" onchange="displayFileName()">
-<div id="fileNameDisplay"></div>
-<button onclick="invokeJS()">调用download</button>
-<button onclick="invokeCamera()">调用相机</button>
-<button onclick="selectFile()">Select File</button>
-<div id="fileDisplay"></div>
-
-<script>
-        function displayFileName() {
-            const fileInput = document.getElementById('fileInput');
-            const fileNameDisplay = document.getElementById('fileNameDisplay');
-            if (fileInput.files.length > 0) {
-                fileNameDisplay.textContent = fileInput.files[0].name;
-            } else {
-                fileNameDisplay.textContent = '';
-            }
-        }
-
-        function invokeJS() {
-           openHarmonyBridge.download(JSON.stringify({
-              token: "ddddd",
-              path: "这是路径"
-            }));
-        }
-
-        function invokeCamera() {
-           let promise = navigator.mediaDevices.getUserMedia(constraints);
-            // then()异步,调用MediaStream对象作为参数
-            promise.then(function (MediaStream) {
-
-            });
-        }
-
-        function selectFile() {
-            const fileInput = document.getElementById('fileInput');
-            fileInput.click();
-        }
-
-        document.getElementById('fileInput').addEventListener('change', function() {
-            const fileDisplay = document.getElementById('fileDisplay');
-            const fileInput = document.getElementById('fileInput');
-            if (fileInput.files.length > 0) {
-                const file = fileInput.files[0];
-                const reader = new FileReader();
-                reader.onload = function(e) {
-                    fileDisplay.textContent = e.target.result;
-                };
-                reader.readAsText(file);
-            } else {
-                fileDisplay.textContent = '';
-            }
-            console.log("dddd")
-        });
-
-
-
-
-
-
-
-
-
-
-
-</script>
-</body>
-</html>

+ 0 - 20
entry/src/main/resources/rawfile/download.html

@@ -1,20 +0,0 @@
-<!DOCTYPE html>
-<html>
-<body>
-<button type="button" onclick="callArkTS()" style="width: 500px;height: 500px">执行Register的方法</button>
-<p id="demo"></p>
-<script>
-    function callArkTS() {
-
-      window.openHarmonyBridge.download("哈哈哈哈哈哈");
-
-
-
-    }
-
-
-
-
-</script>
-</body>
-</html>

+ 0 - 47
entry/src/main/resources/rawfile/local.html

@@ -1,47 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
-    <meta charset="UTF-8">
-    <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <title>File Input Example</title>
-</head>
-<body>
-<input type="file" id="fileInput" onchange="displayFileName()">
-<div id="fileNameDisplay"></div>
-<button onclick="selectFile()">Select File</button>
-<div id="fileDisplay"></div>
-
-<script>
-        function displayFileName() {
-            const fileInput = document.getElementById('fileInput');
-            const fileNameDisplay = document.getElementById('fileNameDisplay');
-            if (fileInput.files.length > 0) {
-                fileNameDisplay.textContent = fileInput.files[0].name;
-            } else {
-                fileNameDisplay.textContent = '';
-            }
-        }
-
-        function selectFile() {
-            const fileInput = document.getElementById('fileInput');
-            fileInput.click();
-        }
-
-        document.getElementById('fileInput').addEventListener('change', function() {
-            const fileDisplay = document.getElementById('fileDisplay');
-            const fileInput = document.getElementById('fileInput');
-            if (fileInput.files.length > 0) {
-                const file = fileInput.files[0];
-                const reader = new FileReader();
-                reader.onload = function(e) {
-                    fileDisplay.textContent = e.target.result;
-                };
-                reader.readAsText(file);
-            } else {
-                fileDisplay.textContent = '';
-            }
-        });
-
-</script>
-</body>
-</html>