Browse Source

feat(http): 完善上传文件逻辑

- 在 HttpHelper 中添加上传进度回调
- 更新 HosApiUtils 中的 upload 方法,支持进度回调
- 在 HttpHelperX 中添加 onProgress 参数
- 更新 CHANGELOG 和 README 文档,记录新功能
xuqm 1 week ago
parent
commit
a900f12af1
4 changed files with 64 additions and 24 deletions
  1. 1 0
      CHANGELOG.md
  2. 56 22
      README.md
  3. 5 2
      src/main/ets/http/HttpHelper.ets
  4. 2 0
      src/main/ets/http/HttpHelperX.ts

+ 1 - 0
CHANGELOG.md

@@ -3,6 +3,7 @@
 > - `RefreshView`参数不包含`onLoadMore`的时候,上划不应该提示`没有更多数据了`
 > - `RefreshView`添加一个`controller`,补充跳转到顶部,跳转到底部等方法,具体见文档`4.3`注释
 > - `WindowHelper`添加一个获取屏幕宽高的方法
+> - `HttpHelper`上传文件逻辑完善
 >
 
 # [v1.0.8] 2025.03.11

+ 56 - 22
README.md

@@ -358,19 +358,10 @@ struct MyView{
 ### 3.1.get请求
 
 ```tsx
-
 HttpHelper.get()
-    .get<HttpResult<T>>(url.url.startsWith('http') ? url.url : GlobalValue.getInstance().envUrl + url.url,
+    .get<HttpResult<T>>(url,
                         data ? JSON.stringify(data) : undefined, {
-    userId: GlobalValue.getInstance().userIds,
-    clientId: GlobalValue.getInstance().getClientIds(),
-    version: ConstantValue.VERSION,
-    deviceType: '01',
-    timeStamp: timeStamp + '',
-    sign: sign,
-    phoneModel: 'sign',
-    phoneVersion: 'sign',
-    phoneBrand: 'HarmonyOS'
+    version: ConstantValue.VERSION
 }, url.apiNo)
     .then((res: HttpResult<T>) => {
     if (res.status === '0') {
@@ -390,18 +381,10 @@ HttpHelper.get()
 ```tsx
 
 HttpHelper.get()
-    .post<HttpResult<T>>(url.url.startsWith('http') ? url.url : GlobalValue.getInstance().envUrl + url.url,
+    .post<HttpResult<T>>(url,
                          data ? JSON.stringify(data) : undefined, {
-    userId: GlobalValue.getInstance().userIds,
-    clientId: GlobalValue.getInstance().getClientIds(),
-    version: ConstantValue.VERSION,
-    deviceType: '01',
-    timeStamp: timeStamp + '',
-    sign: sign,
-    phoneModel: 'sign',
-    phoneVersion: 'sign',
-    phoneBrand: 'HarmonyOS'
-}, url.apiNo)
+    version: ConstantValue.VERSION
+}, apiNo)
     .then((res: HttpResult<T>) => {
     if (res.status === '0') {
         resolve(res.data as T)
@@ -415,6 +398,57 @@ HttpHelper.get()
 })
 ```
 
+### 3.3.postForm
+
+```tsx
+HttpHelper.get()
+        .postForm<HttpResult<T>>({
+          url: '',
+          data: data,
+          headers: {
+            version: ConstantValue.VERSION,
+            deviceId: GlobalValue.getInstance().deviceId,
+          }
+        }, apiNo, showLog)
+        .then((res: HttpResult<T>) => {
+          if (res.status === '0' || res.code === 200) {
+            resolve(res.data as T)
+          } else {
+            reject(new YWXError(res.status ?? res.code?.toString() ?? '-1', res.message))
+          }
+        })
+        .catch((error: Error) => {
+          reject(new YWXError(error.name ?? '-1', error.message))
+        })
+```
+
+### 3.4.upload
+
+```tsx
+HttpHelper.get()
+        .upload<HttpResult<T>>({
+          url: url,
+          data: data,
+          onProgress,
+          headers: {
+            'X-Access-Token': HosGlobalValue.getInstance().token,
+          }
+        }, apiNo, showLog)
+        .then((res: HttpResult<T>) => {
+          if (res.code === 200) {
+            resolve(res.data as T)
+          } else if (res.code === 40003) {
+            AccountManager.get().logout()
+            ToolsHelper.showMessage('登录已过期,请重新登录')
+          } else {
+            reject(new YWXError(res.code?.toString() ?? '-1', res.message))
+          }
+        })
+        .catch((error: Error) => {
+          reject(new YWXError(error.name ?? '-1', error.message))
+        })
+```
+
 ## 4.[自定义view](./src/main/ets/view)
 
 ### 4.1.[LoadingView](./src/main/ets/view/LoadingView.ets)

+ 5 - 2
src/main/ets/http/HttpHelper.ets

@@ -1,6 +1,6 @@
 import { ArrayList, HashMap } from '@kit.ArkTS';
 import http from '@ohos.net.http';
-import { LogHelper, ToolsHelper } from '../../../../Index';
+import { LogHelper } from '../../../../Index';
 import { SZYXLocalStorageHelper } from '../utils/SZYXLocalStorageHelper';
 import { SZYXLocalStorageKeys } from '../utils/SZYXLocalStorageKeys';
 import { HttpHelperX, HttpParamsForm, HttpParamsGet, HttpParamsPost, HttpParamsUpload } from './HttpHelperX';
@@ -341,7 +341,10 @@ export class HttpHelper {
         LogHelper.debug(`postJson:${apiNo}\n`, JSON.stringify(params))
       }
       httpRequest.on("dataSendProgress", (data: http.DataSendProgressInfo) => {
-        ToolsHelper.log(`${apiNo}:\n${JSON.stringify(data)}`)
+        if (showLog) {
+          LogHelper.debug(`${apiNo}:\n${JSON.stringify(data)}`)
+        }
+        params.onProgress && params.onProgress(data.sendSize, data.totalSize)
       });
       httpRequest.request(HttpHelperX.getUrl(params.url, params.query), {
         method: http.RequestMethod.POST,

+ 2 - 0
src/main/ets/http/HttpHelperX.ts

@@ -13,11 +13,13 @@ export interface HttpParamsPost {
   query?: Record<string, string> | Object
   headers?: Record<string, string | null | undefined>
 }
+
 export interface HttpParamsUpload {
   url: string
   data: http.MultiFormData[]
   query?: Record<string, string> | Object
   headers?: Record<string, string | null | undefined>
+  onProgress?: (progress: number, total: number) => void
 }
 
 export interface HttpParamsForm {