|
@@ -0,0 +1,395 @@
|
|
|
+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}`);
|
|
|
+ //
|
|
|
+ // }
|
|
|
+ //
|
|
|
+ //
|
|
|
+ // }
|
|
|
+}
|