当前位置:   article > 正文

HarmonyOS上传文件以及权限授权_harmonyos中axios上传文件

harmonyos中axios上传文件

搞了一天,差不多搞完了,记录下,目前官方还有一些问题 会在下一个next版本修复

0、实现效果

鸿蒙实现图片上传

1、准备页面

  1. build() {
  2. Row() {
  3. Column() {
  4. Button('选择图片28')
  5. .onClick(this.onChooseImage)
  6. // 显示选中的图片(本地地址 非http)
  7. ForEach(this.showChooseImage, (item, idnex) => {
  8. Image(item).width(80).height(80).margin({bottom: 20})
  9. })
  10. // 为了方便展示选中的图片信息
  11. ForEach(this.showListData, (item, idnex) => {
  12. Text(item.path)
  13. })
  14. }
  15. .width('100%')
  16. }
  17. .height('100%')
  18. }

2、授权逻辑

点击“选中图片28”之后,需要先判断是否有读写图片的权限。如果有走后面的流程,如果没有,需要系统弹窗让用户去授权。如果用户授权了,走后面的逻辑;如果用户不授权需要提示用户去系统里面的应用列表去授权(也可以不做这个操作)。

官方文档:文档中心

3、判断是否授权媒体

  1. import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
  2. let atManager = abilityAccessCtrl.createAtManager();
  3. import bundleManager from '@ohos.bundle.bundleManager';
  4. // let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT;
  5. let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION;
  6. // let tokenID = bundleFlags;
  7. let tokenID
  8. import common from '@ohos.app.ability.common';
  9. import picker from '@ohos.file.picker';
  10. import request from '@ohos.request';
  11. let context = getContext(this) as common.UIAbilityContext;
  12. /**
  13. * 对应用权限进行校验封装 我这边默认只能一个一个授权,多个授权自己封装
  14. */
  15. export const permissionsIsAllow = async (type: Permissions, cb:Function) => {
  16. let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleFlags);
  17. let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
  18. tokenID = appInfo.accessTokenId;
  19. console.log('tokenID', tokenID)
  20. try {
  21. atManager.checkAccessToken(tokenID, type).then((data) => {
  22. console.log(`${type} success, data->${JSON.stringify(data)}`);
  23. if (data === 0) { // 已授权
  24. cb()
  25. } else { // 未授权
  26. AlertDialog.show(
  27. {
  28. title: '温馨提示',
  29. message: '您还没有授权',
  30. autoCancel: false,
  31. alignment: DialogAlignment.Bottom,
  32. gridCount: 4,
  33. primaryButton: {
  34. value: '取消授权',
  35. action: () => {
  36. console.info('Callback when the first button is clicked')
  37. AlertDialog.show(
  38. {
  39. title: '温馨提示',
  40. message: '必须要授权才能使用,是否前往应用进行授权',
  41. autoCancel: false,
  42. alignment: DialogAlignment.Bottom,
  43. gridCount: 4,
  44. primaryButton: {
  45. value: '取消',
  46. action: () => {
  47. console.warn('用户再次取消授权')
  48. }
  49. },
  50. secondaryButton: {
  51. value: '前往授权',
  52. action: () => {
  53. let wantInfo = {
  54. action: 'action.settings.app.info',
  55. parameters: {
  56. settingsParamBundleName: 'com.example.medicaltreatment' // 打开指定应用的详情页面
  57. }
  58. }
  59. context.startAbility(wantInfo).then((data) => {
  60. // ...
  61. console.info('前往授权页面成功', JSON.stringify(data))
  62. }).catch((err) => {
  63. // ...
  64. console.error('前往授权页面失败', JSON.stringify(err))
  65. })
  66. }
  67. }
  68. }
  69. )
  70. }
  71. },
  72. secondaryButton: {
  73. value: '确认授权',
  74. action: () => {
  75. atManager.requestPermissionsFromUser(context, [type]).then((data) => {
  76. console.info("data:" + JSON.stringify(data));
  77. console.info("data permissions:" + data.permissions);
  78. console.info("data authResults:", JSON.stringify(data.authResults));
  79. let length: number = data.authResults.length;
  80. for (let i = 0; i < length; i++) {
  81. if (data.authResults[i] === 0) {
  82. // 用户授权,可以继续访问目标操作
  83. cb()
  84. } else {
  85. // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
  86. return;
  87. }
  88. }
  89. }).catch((err) => {
  90. console.info("data:" + JSON.stringify(err));
  91. })
  92. }
  93. },
  94. cancel: () => {
  95. console.info('Closed callbacks')
  96. }
  97. }
  98. )
  99. }
  100. }).catch((err) => {
  101. console.warn(`${type} fail, err->${JSON.stringify(err)}`);
  102. });
  103. } catch(err) {
  104. console.log(`catch err->${JSON.stringify(err)}`);
  105. }
  106. }

效果:

4、选择图片

  1. /**
  2. * 选择图片 单/多
  3. */
  4. export const chooseImage = (cb: Function, number: number) => {
  5. try {
  6. let PhotoSelectOptions = new picker.PhotoSelectOptions();
  7. PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
  8. PhotoSelectOptions.maxSelectNumber = number;
  9. let photoPicker = new picker.PhotoViewPicker();
  10. photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
  11. console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
  12. console.log('PhotoSelectResult111', PhotoSelectResult)
  13. if (PhotoSelectResult && PhotoSelectResult.photoUris) {
  14. const imgList = PhotoSelectResult.photoUris;
  15. cb(imgList)
  16. }
  17. }).catch((err) => {
  18. console.error('PhotoViewPicker.select failed with err: ' + err);
  19. });
  20. } catch (err) {
  21. console.error('PhotoViewPicker failed with err: ' + err);
  22. }
  23. }

选中的图片的路径是这样的:

5、将datashare的路径进行转换

为什么要转换: 看官方文档:文档中心

  1. private onDealWithData = (fileUris: string[]) => {
  2. console.log('appLog:fileUris:', JSON.stringify(fileUris));
  3. this.showChooseImage = fileUris
  4. this.onUploadImageFileList = []
  5. const promises = fileUris.map(async item => await this.onPromiseTask(item));
  6. Promise.all(promises)
  7. .then(() => {
  8. console.log("All tasks completed. Proceed to the next step.");
  9. if (this.onUploadImageFileList.length > 0) {
  10. this.onUploadFile(this.onUploadImageFileList);
  11. } else {
  12. console.log('onUploadImageFileList的长度为0')
  13. }
  14. // 在这里执行下一步操作
  15. })
  16. .catch(error => {
  17. console.error("Error occurred:", error);
  18. });
  19. }
  20. private onPromiseTask = (v) => {
  21. return new Promise((resolve, reject) => {
  22. fs.open(v, fs.OpenMode.READ_ONLY).then((file) => { // READ_ONLY READ_WRITE
  23. const dateStr = (new Date().getTime()).toString()
  24. let newPath = context.cacheDir + `/${dateStr}.png`;
  25. fs.copyFile(file.fd, newPath).then(() => {
  26. console.info("applog:copy file succeed");
  27. let realUri = "internal://cache/"+newPath.split("cache/")[1];
  28. const obj = {
  29. filename: `${dateStr}.png`,
  30. name: "files",
  31. uri: realUri,
  32. type: "png"
  33. }
  34. this.onUploadImageFileList.push(obj);
  35. resolve(true)
  36. }).catch((err) => {
  37. console.info("applog:copy file failed with error message: " + err.message + ", error code: " + err.code);
  38. });
  39. }).catch((err) => {
  40. console.info("applog:open file failed with error message: " + err.message + ", error code: " + err.code);
  41. });
  42. })
  43. }

转换好之后的文件路径是这样的:

6、上传到服务器

  1. /**
  2. * 上传图片
  3. */
  4. export const uploadImageListOrSingle = async (files, cb:Function) => {
  5. const token = await PreferenceModel.getPreference('tokenInfo', 'token')
  6. const uploadConfigData = []
  7. console.info('转换之后的files', JSON.stringify(files))
  8. files.forEach(v => {
  9. const uploadConfig = {
  10. url: 'https://xxx.xxx.xxx/api/v1.0/oss/upload',
  11. header: {
  12. 'Hwkj-Custom-Client': 'PlatformOfWeb',
  13. "Authorization": token ? 'Bearer ' + token : '',
  14. },
  15. method: "POST",
  16. files: [v],
  17. data: [{ name: "files", value: "files"}],
  18. }
  19. uploadConfigData.push(uploadConfig)
  20. })
  21. const promises = uploadConfigData.map(async item => await onGetImageUploadBackUrl(item));
  22. Promise.all(promises)
  23. .then((data) => {
  24. const showList = []
  25. data.forEach(v => {
  26. showList.push(v[0])
  27. })
  28. cb(showList)
  29. })
  30. .catch(error => {
  31. console.error("Error occurred1:", error);
  32. });
  33. }
  34. const onGetImageUploadBackUrl = (uploadConfig) => {
  35. let uploadTask;
  36. return new Promise((resolve, reject) => {
  37. try {
  38. request.uploadFile( getContext(this), uploadConfig).then((data) => {
  39. console.info('JSON.stringify(data)', JSON.stringify(data))
  40. uploadTask = data;
  41. let upProgressCallback = (data) => {
  42. console.info("data1111:" + JSON.stringify(data));
  43. resolve(data)
  44. };
  45. uploadTask.on('complete', upProgressCallback);
  46. }).catch((err) => {
  47. console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
  48. });
  49. } catch (err) {
  50. console.error('applog:', JSON.stringify(err));
  51. console.error('err.code : ' + err.code + ', err.message : ' + err.message);
  52. }
  53. })
  54. }

6、显示选中的和上传接口返回的数据信息(效果图)

注意事项:

1、不知道为什么checkAccessToken永远走的.catch,不知道是代码原因还是本来这个api的原因。导致用户同意授权之后,下一次仍然是未授权。目前还未解决,还在等官方的回答(已解决 上方的代码已经解决了)

2、大家可以看到 当通过上传接口返回的数据并不是服务器返回的数据而是官方返回的图片信息

我已经对这个问题给官方说了:

“我们这个上传接口会返回一个图片的url 但是现在执行complete之后 返回的并不是服务器返回的数据 这种情况怎么办呢?”

官方的回答是:

7、完整代码

1、页面ui代码

  1. import fs from '@ohos.file.fs';
  2. import common from '@ohos.app.ability.common';
  3. let context = getContext(this) as common.UIAbilityContext;
  4. import { permissionsIsAllow, chooseImage, uploadImageListOrSingle } from '../../utils'
  5. @Entry
  6. @Component
  7. struct AccountSettingIndex {
  8. @State showListData: any[] = []
  9. @State showChooseImage: any[] = []
  10. @State onUploadImageFileList: any[] = []
  11. private onChooseImage = () => {
  12. permissionsIsAllow('ohos.permission.WRITE_MEDIA', () => { // READ_MEDIA
  13. this.onChooseImageFin()
  14. })
  15. }
  16. private onChooseImageFin = () => {
  17. chooseImage((imgList) => {
  18. this.onDealWithData(imgList)
  19. }, 2)
  20. }
  21. private onDealWithData = (fileUris: string[]) => {
  22. console.log('appLog:fileUris:', JSON.stringify(fileUris));
  23. this.showChooseImage = fileUris
  24. this.onUploadImageFileList = []
  25. const promises = fileUris.map(async item => await this.onPromiseTask(item));
  26. Promise.all(promises)
  27. .then(() => {
  28. console.log("All tasks completed. Proceed to the next step.");
  29. if (this.onUploadImageFileList.length > 0) {
  30. this.onUploadFile(this.onUploadImageFileList);
  31. } else {
  32. console.log('onUploadImageFileList的长度为0')
  33. }
  34. // 在这里执行下一步操作
  35. })
  36. .catch(error => {
  37. console.error("Error occurred:", error);
  38. });
  39. }
  40. private onPromiseTask = (v) => {
  41. return new Promise((resolve, reject) => {
  42. fs.open(v, fs.OpenMode.READ_ONLY).then((file) => { // READ_ONLY READ_WRITE
  43. const dateStr = (new Date().getTime()).toString()
  44. let newPath = context.cacheDir + `/${dateStr}.png`;
  45. fs.copyFile(file.fd, newPath).then(() => {
  46. console.info("applog:copy file succeed");
  47. let realUri = "internal://cache/"+newPath.split("cache/")[1];
  48. const obj = {
  49. filename: `${dateStr}.png`,
  50. name: "files",
  51. uri: realUri,
  52. type: "png"
  53. }
  54. this.onUploadImageFileList.push(obj);
  55. resolve(true)
  56. }).catch((err) => {
  57. console.info("applog:copy file failed with error message: " + err.message + ", error code: " + err.code);
  58. });
  59. }).catch((err) => {
  60. console.info("applog:open file failed with error message: " + err.message + ", error code: " + err.code);
  61. });
  62. })
  63. }
  64. private onUploadFile = async (fileUri) => {
  65. uploadImageListOrSingle(fileUri, (data) => {
  66. console.log('获取到的url是', typeof data ,data)
  67. this.showListData = data
  68. })
  69. }
  70. build() {
  71. Row() {
  72. Column() {
  73. Button('选择图片28')
  74. .onClick(this.onChooseImage)
  75. // 显示选中的图片
  76. ForEach(this.showChooseImage, (item, idnex) => {
  77. Image(item).width(80).height(80).margin({bottom: 20})
  78. })
  79. // 为了方便展示选中的图片信息
  80. ForEach(this.showListData, (item, idnex) => {
  81. Text(item.path)
  82. })
  83. }
  84. .width('100%')
  85. }
  86. .height('100%')
  87. }
  88. }

2、utils文件下面的三个方法

  1. import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
  2. let atManager = abilityAccessCtrl.createAtManager();
  3. import bundleManager from '@ohos.bundle.bundleManager';
  4. // let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT;
  5. let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION;
  6. // let tokenID = bundleFlags;
  7. let tokenID
  8. import common from '@ohos.app.ability.common';
  9. import picker from '@ohos.file.picker';
  10. import request from '@ohos.request';
  11. let context = getContext(this) as common.UIAbilityContext;
  12. /**
  13. * 对应用权限进行校验封装 我这边默认只能一个一个授权,多个授权自己封装
  14. */
  15. export const permissionsIsAllow = async (type: Permissions, cb:Function) => {
  16. let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleFlags);
  17. let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
  18. tokenID = appInfo.accessTokenId;
  19. console.log('tokenID', tokenID)
  20. try {
  21. atManager.checkAccessToken(tokenID, type).then((data) => {
  22. console.log(`${type} success, data->${JSON.stringify(data)}`);
  23. if (data === 0) { // 已授权
  24. cb()
  25. } else { // 未授权
  26. AlertDialog.show(
  27. {
  28. title: '温馨提示',
  29. message: '您还没有授权',
  30. autoCancel: false,
  31. alignment: DialogAlignment.Bottom,
  32. gridCount: 4,
  33. primaryButton: {
  34. value: '取消授权',
  35. action: () => {
  36. console.info('Callback when the first button is clicked')
  37. AlertDialog.show(
  38. {
  39. title: '温馨提示',
  40. message: '必须要授权才能使用,是否前往应用进行授权',
  41. autoCancel: false,
  42. alignment: DialogAlignment.Bottom,
  43. gridCount: 4,
  44. primaryButton: {
  45. value: '取消',
  46. action: () => {
  47. console.warn('用户再次取消授权')
  48. }
  49. },
  50. secondaryButton: {
  51. value: '前往授权',
  52. action: () => {
  53. let wantInfo = {
  54. action: 'action.settings.app.info',
  55. parameters: {
  56. settingsParamBundleName: 'com.example.medicaltreatment' // 打开指定应用的详情页面
  57. }
  58. }
  59. context.startAbility(wantInfo).then((data) => {
  60. // ...
  61. console.info('前往授权页面成功', JSON.stringify(data))
  62. }).catch((err) => {
  63. // ...
  64. console.error('前往授权页面失败', JSON.stringify(err))
  65. })
  66. }
  67. }
  68. }
  69. )
  70. }
  71. },
  72. secondaryButton: {
  73. value: '确认授权',
  74. action: () => {
  75. atManager.requestPermissionsFromUser(context, [type]).then((data) => {
  76. console.info("data:" + JSON.stringify(data));
  77. console.info("data permissions:" + data.permissions);
  78. console.info("data authResults:", JSON.stringify(data.authResults));
  79. let length: number = data.authResults.length;
  80. for (let i = 0; i < length; i++) {
  81. if (data.authResults[i] === 0) {
  82. // 用户授权,可以继续访问目标操作
  83. cb()
  84. } else {
  85. // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
  86. return;
  87. }
  88. }
  89. }).catch((err) => {
  90. console.info("data:" + JSON.stringify(err));
  91. })
  92. }
  93. },
  94. cancel: () => {
  95. console.info('Closed callbacks')
  96. }
  97. }
  98. )
  99. }
  100. }).catch((err) => {
  101. console.warn(`${type} fail, err->${JSON.stringify(err)}`);
  102. });
  103. } catch(err) {
  104. console.log(`catch err->${JSON.stringify(err)}`);
  105. }
  106. }
  107. /**
  108. * 选择图片 单/多
  109. */
  110. export const chooseImage = (cb: Function, number: number) => {
  111. try {
  112. let PhotoSelectOptions = new picker.PhotoSelectOptions();
  113. PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
  114. PhotoSelectOptions.maxSelectNumber = number;
  115. let photoPicker = new picker.PhotoViewPicker();
  116. photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
  117. console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
  118. console.log('PhotoSelectResult111', PhotoSelectResult)
  119. if (PhotoSelectResult && PhotoSelectResult.photoUris) {
  120. const imgList = PhotoSelectResult.photoUris;
  121. cb(imgList)
  122. }
  123. }).catch((err) => {
  124. console.error('PhotoViewPicker.select failed with err: ' + err);
  125. });
  126. } catch (err) {
  127. console.error('PhotoViewPicker failed with err: ' + err);
  128. }
  129. }
  130. /**
  131. * 上传图片
  132. */
  133. export const uploadImageListOrSingle = async (files, cb:Function) => {
  134. const token = await PreferenceModel.getPreference('tokenInfo', 'token')
  135. const uploadConfigData = []
  136. console.info('转换之后的files', JSON.stringify(files))
  137. files.forEach(v => {
  138. const uploadConfig = {
  139. url: 'https://xxx.xxx.com/api/v1.0/oss/upload',
  140. header: {
  141. 'Hwkj-Custom-Client': 'PlatformOfWeb',
  142. "Authorization": token ? 'Bearer ' + token : '',
  143. },
  144. method: "POST",
  145. files: [v],
  146. data: [{ name: "files", value: "files"}],
  147. }
  148. uploadConfigData.push(uploadConfig)
  149. })
  150. const promises = uploadConfigData.map(async item => await onGetImageUploadBackUrl(item));
  151. Promise.all(promises)
  152. .then((data) => {
  153. const showList = []
  154. data.forEach(v => {
  155. showList.push(v[0])
  156. })
  157. cb(showList)
  158. })
  159. .catch(error => {
  160. console.error("Error occurred1:", error);
  161. });
  162. }
  163. const onGetImageUploadBackUrl = (uploadConfig) => {
  164. let uploadTask;
  165. return new Promise((resolve, reject) => {
  166. try {
  167. request.uploadFile( getContext(this), uploadConfig).then((data) => {
  168. console.info('JSON.stringify(data)', JSON.stringify(data))
  169. uploadTask = data;
  170. let upProgressCallback = (data) => {
  171. console.info("data1111:" + JSON.stringify(data));
  172. resolve(data)
  173. };
  174. uploadTask.on('complete', upProgressCallback);
  175. }).catch((err) => {
  176. console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
  177. });
  178. } catch (err) {
  179. console.error('applog:', JSON.stringify(err));
  180. console.error('err.code : ' + err.code + ', err.message : ' + err.message);
  181. }
  182. })
  183. }

上一章:HarmonyOS自定义标题栏-CSDN博客

下一章:HarmonyOS文件下载以及消息通知-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/296946
推荐阅读
相关标签
  

闽ICP备14008679号