HarmonyOS应用四之页面加载构建以及数据请求

news2024/11/14 18:17:07

目录:

    • 1、加载网络页面/本地页面/html页面
    • 2、页面布局
    • 3、HTTP/HTTPS的数据请求
    • 4、上传图片并保存数据

1、加载网络页面/本地页面/html页面

// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();

  build() {
    Column() {
      Button('loadUrl')
        .onClick(() => {
          try {
            // 点击按钮时,通过loadUrl,跳转到www.example1.com
            this.controller.loadUrl('www.example1.com');
            // 点击按钮时,通过loadUrl,跳转到local1.html
            this.controller.loadUrl($rawfile("local1.html"));
              // 点击按钮时,通过loadData,加载HTML格式的文本数据
            this.controller.loadData(
              "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>",
              "text/html",
              "UTF-8"
            );
          } catch (error) {
            let e: BusinessError = error as BusinessError;
            console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
          }
        })
      // 组件创建时,加载www.example.com
      Web({ src: 'www.example.com', controller: this.controller})
    }
  }
}

2、页面布局

2.1示例:
在这里插入图片描述

// import { CourseLearning } from '@ohos/learning';
import { KnowledgeMap } from '@ohos/map';

@Entry
@Component
struct Index {
  build() {
    Column() {
      // CourseLearning()
      KnowledgeMap()
    }
    .backgroundColor('#F1F3F5')
    .padding({ top: 36, bottom: 28 })
  }
}
import { util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
import { Section } from '../view/KnowledgeMapContent';
import { NavBarItem, NavBarItemType } from '../view/NavBarItem';

@Component
export struct KnowledgeMap {
  @State navBarList: NavBarItemType[] = [
    { order: '01', title: '准备与学习' },
    { order: '02', title: '构建应用' },
    { order: '03', title: '应用测试' },
    { order: '04', title: '上架' },
    { order: '05', title: '运营增长' },
    { order: '06', title: '商业变现' },
    { order: '07', title: '更多' }
  ];
  @State sections: Section[] = [];

  private getSections() {
    try {
      getContext(this).resourceManager.getRawFileContent("MapData.json", (error: BusinessError, value: Uint8Array) => {
        const textDecoder = util.TextDecoder.create("utf-8");
        const res = textDecoder.decodeWithStream(value, { stream: false });
        this.sections = JSON.parse(res);
      });
    } catch (error) {
      console.error(`callback getRawFileContent failed, error is ${JSON.stringify(error)}`)
    }
  }

  aboutToAppear(): void {
    this.getSections();
  }

  build() {
    Scroll() {
      Column() {
        Text('知识地图')
          .fontFamily('HarmonyHeiTi-Bold')
          .fontSize(24)
          .fontColor(Color.Black)
          .textAlign(TextAlign.Start)
          .lineHeight(33)
          .fontWeight(700)
          .width('100%')
        Image($r("app.media.knowledge_map_banner"))
          .width('100%')
          .borderRadius(16)
          .margin({ top: 19, bottom: 8 })
        Text('通过循序渐进的学习路径,无经验和有经验的开发者都可以轻松掌握ArkTS语言声明式开发范式,体验更简洁、更友好的HarmonyOS应用开发旅程。')
          .fontFamily('HarmonyHeiTi')
          .fontSize('14vp')
          .fontColor('rgba(0,0,0,0.60)')
          .fontWeight(400)
          .textAlign(TextAlign.Start)

        List({ space: 12 }) {
          ForEach(this.navBarList, (item: NavBarItemType, index: number) => {
            ListItem() {
              NavBarItem({ navBarItem: item })
            }
            .width('100%')
          }, (item: NavBarItemType): string => item.title)
        }
        .width('100%')
        .margin({ top: 24 })
      }
      .padding({
        top: 12,
        right: 16,
        bottom: 12,
        left: 16
      })
    }
    .backgroundColor('#F1F3F5')
    .align(Alignment.TopStart)
    .constraintSize({ minHeight: '100%' })
    .scrollable(ScrollDirection.Vertical)
    .scrollBar(BarState.Auto)
    .scrollBarColor(Color.Gray)
    .edgeEffect(EdgeEffect.Spring)
  }
}

2.2示例:
在这里插入图片描述

import { CourseLearning } from '@ohos/learning';
import { KnowledgeMap } from '@ohos/map';
import { QuickStartPage } from '@ohos/quickstart';

@Entry
@Component
struct Index {
  @State currentIndex: number = 0;
  private tabsController: TabsController = new TabsController();

  @Builder
  tabBarBuilder(title: string, targetIndex: number, selectedIcon: Resource, unselectIcon: Resource) {
    Column() {
      Image(this.currentIndex === targetIndex ? selectedIcon : unselectIcon)
        .width(24)
        .height(24)
      Text(title)
        .fontFamily('HarmonyHeiTi-Medium')
        .fontSize(10)
        .fontColor(this.currentIndex === targetIndex ? '#0A59F7' : 'rgba(0,0,0,0.60)')
        .textAlign(TextAlign.Center)
        .lineHeight(14)
        .fontWeight(500)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)
    .onClick(() => {
      this.currentIndex = targetIndex;
      this.tabsController.changeIndex(targetIndex);
    })
  }

  build() {
    Tabs({ barPosition: BarPosition.End, controller: this.tabsController }) {
      TabContent() {
        QuickStartPage()
      }
      .tabBar(this.tabBarBuilder('快速入门', 0, $r('app.media.ic_01_on'), $r('app.media.ic_01_off')))

      TabContent() {
        CourseLearning()
      }
      .tabBar(this.tabBarBuilder('课程学习', 1, $r('app.media.ic_02_on'), $r('app.media.ic_02_off')))

      TabContent() {
        KnowledgeMap()
      }
      .tabBar(this.tabBarBuilder('知识地图', 2, $r('app.media.ic_03_on'), $r('app.media.ic_03_off')))
    }
    .vertical(false)
    .divider({
      strokeWidth: 0.5,
      color: '#0D182431'
    })
    .scrollable(false)
    .backgroundColor('#F1F3F5')
    .padding({ top: 36, bottom: 28 })
  }
}
import { TutorialView } from '../view/TutorialView';
import { ArticleClass } from '../model/ArticleClass'
import { ArticleDetailPage } from './ArticleDetailPage';
import { Banner } from '../view/Banner';
import { EnablementView } from '../view/EnablementView';
import { BannerDetailPage } from './BannerDetailPage';
import { BannerClass } from '../model/BannerClass';

@Component
export struct QuickStartPage {
  @State message: string = '快速入门';
  @Provide('articlePathStack') articlePathStack: NavPathStack = new NavPathStack();

  @Builder
  quickStartRouter(name: string, param?: ArticleClass | BannerClass) {
    if (name === 'articleDetail') {
      ArticleDetailPage()
    } else if (name === 'bannerDetailPage') {
      BannerDetailPage()
    }
  }

  build() {
    Navigation(this.articlePathStack) {
      Column() {
        Text(this.message)
          .fontSize(24)
          .fontWeight(700)
          .width('100%')
          .textAlign(TextAlign.Start)
          .padding({ left: 16 })
          .fontFamily('HarmonyHeiTi-Bold')
          .lineHeight(33)
        Scroll() {
          Column() {
            Banner()
            EnablementView()
            TutorialView()
          }
        }
        .layoutWeight(1)
        .scrollBar(BarState.Off)
        .align(Alignment.TopStart)
      }
      .width('100%')
      .height('100%')
      .backgroundColor('#F1F3F5')
    }
    .navDestination(this.quickStartRouter)
    .hideTitleBar(true)
    .mode(NavigationMode.Stack)
  }
}
import { webview } from '@kit.ArkWeb';
import { ArticleClass } from '../model/ArticleClass'

@Component
export struct ArticleDetailPage {
  @State webviewController: webview.WebviewController = new webview.WebviewController;
  @Consume('articlePathStack') articlePathStack: NavPathStack;
  @State articleDetail: ArticleClass | null = null;

  aboutToAppear(): void {
    this.articleDetail = this.articlePathStack.getParamByName('articleDetail')[0] as ArticleClass;
  }

  build() {
    NavDestination() {
      Column() {
        Row() {
          Row() {
            Image($r('app.media.ic_back'))
              .width(40)
              .height(40)
              .onClick(() => {
                this.articlePathStack.pop()
              })
            Row() {
              Text(this.articleDetail?.title)
                .fontFamily('HarmonyHeiTi-Bold')
                .fontSize(20)
                .textAlign(TextAlign.Start)
                .textOverflow({ overflow: TextOverflow.Ellipsis })
                .maxLines(1)
                .fontWeight(700)
                .margin({ left: 8 })
            }
          }
          .width('80%')
        }
        .justifyContent(FlexAlign.SpaceBetween)
        .width('100%')
        .height(56)

        WebComponent({ articleDetail: this.articleDetail, webviewController: this.webviewController })
      }
      .padding({ left: 16, right: 16 })
      .width('100%')
      .height('100%')
      .justifyContent(FlexAlign.SpaceBetween)
    }
    .hideTitleBar(true)
  }
}

@Component
struct WebComponent {
  @Prop articleDetail: ArticleClass | null;
  @Prop webviewController: WebviewController;

  build() {
    Column() {
      Web({ src: this.articleDetail?.webUrl, controller: this.webviewController })
        .darkMode(WebDarkMode.Auto)
        .domStorageAccess(true)
        .zoomAccess(true)
        .fileAccess(true)
        .mixedMode(MixedMode.All)
        .cacheMode(CacheMode.None)
        .javaScriptAccess(true)
        .width('100%')
        .layoutWeight(1)
    }
  }
}

3、HTTP/HTTPS的数据请求

  aboutToAppear() {
    // Request news category.
    NewsViewModel.getNewsTypeList().then((typeList: NewsTypeModel[]) => {
      this.tabBarArray = typeList;
    }).catch((typeList: NewsTypeModel[]) => {
      this.tabBarArray = typeList;
    });
  }
/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { CommonConstant as Const } from '../common/constant/CommonConstant';
import { NewsData } from './NewsData';
import NewsTypeModel from './NewsTypeModel';
import { httpRequestGet } from '../common/utils/HttpUtil';
import Logger from '../common/utils/Logger';
import ResponseResult from './ResponseResult';

class NewsViewModel {
  /**
   * Get news type list from server.
   *
   * @return NewsTypeBean[] newsTypeList
   */
  getNewsTypeList(): Promise<NewsTypeModel[]> {
    return new Promise((resolve: Function, reject: Function) => {
      let url = `${Const.SERVER}/${Const.GET_NEWS_TYPE}`;
      httpRequestGet(url).then((data: ResponseResult) => {
        if (data.code === Const.SERVER_CODE_SUCCESS) {
          resolve(data.data);
        } else {
          reject(Const.TabBars_DEFAULT_NEWS_TYPES);
        }
      }).catch(() => {
        reject(Const.TabBars_DEFAULT_NEWS_TYPES);
      });
    });
  }

  /**
   * Get default news type list.
   *
   * @return NewsTypeBean[] newsTypeList
   */
  getDefaultTypeList(): NewsTypeModel[] {
    return Const.TabBars_DEFAULT_NEWS_TYPES;
  }

  /**
   * Get news type list from server.
   *
   * @return NewsData[] newsDataList
   */
  getNewsList(currentPage: number, pageSize: number, path: string): Promise<NewsData[]> {
    return new Promise(async (resolve: Function, reject: Function) => {
      let url = `${Const.SERVER}/${path}`;
      url += '?currentPage=' + currentPage + '&pageSize=' + pageSize;
      httpRequestGet(url).then((data: ResponseResult) => {
        if (data.code === Const.SERVER_CODE_SUCCESS) {
          resolve(data.data);
        } else {
          Logger.error('getNewsList failed', JSON.stringify(data));
          reject($r('app.string.page_none_msg'));
        }
      }).catch((err: Error) => {
        Logger.error('getNewsList failed', JSON.stringify(err));
        reject($r('app.string.http_error_message'));
      });
    });
  }
}

let newsViewModel = new NewsViewModel();

export default newsViewModel as NewsViewModel;

远程请求工具类:

/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { http } from '@kit.NetworkKit';
import ResponseResult from '../../viewmodel/ResponseResult';
import { CommonConstant as Const, ContentType } from '../constant/CommonConstant';


/**
 * Initiates an HTTP request to a given URL.
 *
 * @param url URL for initiating an HTTP request.
 * @param params Params for initiating an HTTP request.
 */
export function httpRequestGet(url: string): Promise<ResponseResult> {
  let httpRequest = http.createHttp();
  let responseResult = httpRequest.request(url, {
    method: http.RequestMethod.GET,
    readTimeout: Const.HTTP_READ_TIMEOUT,
    header: {
      'Content-Type': ContentType.JSON
    },
    connectTimeout: Const.HTTP_READ_TIMEOUT,
    extraData: {}
  });
  let serverData: ResponseResult = new ResponseResult();
  // Processes the data and returns.
  return responseResult.then((value: http.HttpResponse) => {
    if (value.responseCode === Const.HTTP_CODE_200) {
      // Obtains the returned data.
      let result = `${value.result}`;
      let resultJson: ResponseResult = JSON.parse(result);
      if (resultJson.code === Const.SERVER_CODE_SUCCESS) {
        serverData.data = resultJson.data;
      }
      serverData.code = resultJson.code;
      serverData.msg = resultJson.msg;
    } else {
      serverData.msg = `${$r('app.string.http_error_message')}&${value.responseCode}`;
    }
    return serverData;
  }).catch(() => {
    serverData.msg = $r('app.string.http_error_message');
    return serverData;
  })
}

https的数据请求:

  async onRequest() {
    if (this.webVisibility === Visibility.Hidden) {
      this.webVisibility = Visibility.Visible;
      try {
        let result = await httpGet(this.webSrc);
        if (result && result.responseCode === http.ResponseCode.OK) {
          this.controller.clearHistory();
          this.controller.loadUrl(this.webSrc);
        }
      } catch (error) {
        promptAction.showToast({
          message: $r('app.string.http_response_error')
        })
      }
    } else {
      this.webVisibility = Visibility.Hidden;
    }
  }
/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { http } from '@kit.NetworkKit';
import CommonConstant from '../constant/CommonConstants';

/**
 * Initiates an HTTP request to a given URL.
 *
 * @param url URL for initiating an HTTP request.
 * @returns the result of HTTPS.
 */
export default async function httpGet(url: string) {
  if (!url) {
    return undefined;
  }
  let request = http.createHttp();

  let result = await request.request(url, {
    method: http.RequestMethod.GET,
    header: { 'Content-Type': 'application/json' },
    readTimeout: CommonConstant.READ_TIMEOUT,
    connectTimeout: CommonConstant.CONNECT_TIMEOUT
  });
  return result;
}

4、上传图片并保存数据

uploadNewsData() {
    if (this.title === '') {
      showToast($r('app.string.prompt_no_title'));
      return;
    }
    if (this.content === '') {
      showToast($r('app.string.prompt_no_content'));
      return;
    }
    if (this.imageUri === '') {
      showToast($r('app.string.prompt_no_file'));
      return;
    }
    this.isUploading = true;
    let serverData = fileUpload(getContext(this), this.imageUri);
    serverData.then((data: ResponseResult) => {
      let imageUrl = data.data;
      let newsFile = new NewsFile();
      newsFile.id = 0;
      newsFile.url = imageUrl;
      newsFile.type = 0;
      newsFile.newsId = 0;
      let newsData: NewsData = new NewsData();
      newsData.title = this.title;
      newsData.content = this.content;
      newsData.imagesUrl = [newsFile];
      NewsViewModel.uploadNews(newsData).then(() => {
        this.isUploading = false;
        GlobalContext.getContext().setObject('isBackRouter', true);
        router.back();
      }).catch(() => {
        this.isUploading = false;
        showToast($r('app.string.upload_error_message'));
      });
    }).catch(() => {
      this.isUploading = false;
      showToast($r('app.string.upload_error_message'));
    });
  }

  build() {
    Stack() {
      Navigation() {
        Column() {
          Column() {
            TextInput({ placeholder: $r('app.string.title_default_text') })
              .fontSize($r('app.float.title_font'))
              .placeholderFont({ size: $r('app.float.title_font') })
              .margin({ top: $r('app.float.common_padding') })
              .fontColor($r('app.color.title_color'))
              .backgroundColor(Color.White)
              .onChange((value: string) => {
                this.title = value;
              })
              .width(Constants.FULL_PERCENT)
              .height($r('app.float.input_height'))
            Divider()
              .opacity($r('app.float.divider_opacity'))
              .color($r('app.color.title_color'))
              .width(Constants.DIVIDER_WIDTH)
            TextArea({ placeholder: $r('app.string.content_default_text') })
              .placeholderFont({ size: $r('app.float.title_font') })
              .fontColor($r('app.color.title_color'))
              .height($r('app.float.area_height'))
              .fontSize($r('app.float.title_font'))
              .margin({ top: $r('app.float.normal_padding') })
              .backgroundColor(Color.White)
              .onChange((value: string) => {
                this.content = value;
              })
            Scroll() {
              Row() {
                Image(this.imageUri ? this.imageUri : $r('app.media.ic_add_pic'))
                  .width($r('app.float.img_size'))
                  .height($r('app.float.img_size'))
                  .objectFit(ImageFit.Cover)
                  .onClick(() => this.selectImage())
              }
              .padding($r('app.float.common_padding'))
            }
            .width(Constants.FULL_PERCENT)
            .scrollable(ScrollDirection.Horizontal)
            .align(Alignment.Start)
          }
          .borderRadius($r('app.float.edit_view_radius'))
          .backgroundColor(Color.White)
          .width(Constants.FULL_PERCENT)

          Button($r('app.string.release_btn'))
            .fontSize($r('app.float.title_font'))
            .height($r('app.float.release_btn_height'))
            .width($r('app.float.release_btn_width'))
            .margin({ bottom: $r('app.float.common_padding') })
            .onClick(() => this.uploadNewsData())
        }
        .padding({
          left: $r('app.float.common_padding'),
          right: $r('app.float.common_padding'),
          bottom: $r('app.float.common_padding')
        })
        .height(Constants.FULL_PERCENT)
        .justifyContent(FlexAlign.SpaceBetween)
      }
      .height(Constants.FULL_PERCENT)
      .title(Constants.RELEASE_TITLE)
      .titleMode(NavigationTitleMode.Mini)
      .backgroundColor($r('app.color.listColor'))

      if (this.isUploading) {
        UploadingLayout()
      }
    }
  }
 uploadNewsData() {
    if (this.title === '') {
      showToast($r('app.string.prompt_no_title'));
      return;
    }
    if (this.content === '') {
      showToast($r('app.string.prompt_no_content'));
      return;
    }
    if (this.imageUri === '') {
      showToast($r('app.string.prompt_no_file'));
      return;
    }
    this.isUploading = true;
    let serverData = fileUpload(getContext(this), this.imageUri);
    serverData.then((data: ResponseResult) => {
      let imageUrl = data.data;
      let newsFile = new NewsFile();
      newsFile.id = 0;
      newsFile.url = imageUrl;
      newsFile.type = 0;
      newsFile.newsId = 0;
      let newsData: NewsData = new NewsData();
      newsData.title = this.title;
      newsData.content = this.content;
      newsData.imagesUrl = [newsFile];
      NewsViewModel.uploadNews(newsData).then(() => {
        this.isUploading = false;
        GlobalContext.getContext().setObject('isBackRouter', true);
        router.back();
      }).catch(() => {
        this.isUploading = false;
        showToast($r('app.string.upload_error_message'));
      });
    }).catch(() => {
      this.isUploading = false;
      showToast($r('app.string.upload_error_message'));
    });
  }
/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { fileIo } from '@kit.CoreFileKit';
import { request } from '@kit.BasicServicesKit';
import { picker } from '@kit.CoreFileKit';
import Constants, { ContentType, RequestMethod, UploadingState } from '../constants/Constants';
import ResponseResult from '../../viewmodel/ResponseResult';
import Logger from './Logger';
import { showToast } from './ToastUtil';

/**
 * PhotoViewPicker
 *
 * @returns uri The uri for the selected file.
 */
export async function fileSelect(): Promise<string> {
  let photoSelectOptions = new picker.PhotoSelectOptions();
  photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
  photoSelectOptions.maxSelectNumber = 1;
  let photoPicker = new picker.PhotoViewPicker();
  try {
    let photoSelectResult = await photoPicker.select(photoSelectOptions);
    if (photoSelectResult && photoSelectResult.photoUris && photoSelectResult.photoUris.length > 0) {
      let imgUri = photoSelectResult.photoUris[0];
      if (imgUri.indexOf('media/Photo')<0) {
        showToast($r('app.string.prompt_select_img'));
        return '';
      }
      return photoSelectResult.photoUris[0];
    } else {
      return '';
    }
  } catch (err) {
    Logger.error('SelectedImage failed', JSON.stringify(err));
    return '';
  }
}

/**
 * Upload file.
 *
 * @param context Indicates the application BaseContext.
 * @param fileUri The local storage path of the file.
 * @returns the promise returned by the function.
 */
export function fileUpload(context: Context, fileUri: string): Promise<ResponseResult> {
  // Obtaining the Application File Path.
  let cacheDir = context.cacheDir;
  let imgName = fileUri.split('/').pop() + '.jpg';
  let dstPath = cacheDir + '/' + imgName;
  let url: string = Constants.SERVER + Constants.UPLOAD_FILE;
  let uploadRequestOptions: request.UploadConfig = {
    url: url,
    header: {
      'Content-Type': ContentType.FORM
    },
    method: RequestMethod.POST,
    files: [{
      filename: imgName,
      name: 'file',
      uri: 'internal://cache/' + imgName,
      type: 'jpg'
    }],
    data: []
  };

  let serverData = new ResponseResult();
  return new Promise((resolve: Function, reject: Function) => {
    try {
      // Copy the URI to the cacheDir directory and upload the file.
      let srcFile = fileIo.openSync(fileUri);
      let dstFile = fileIo.openSync(dstPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
      fileIo.copyFileSync(srcFile.fd, dstFile.fd);
      fileIo.closeSync(srcFile);
      fileIo.closeSync(dstFile);

      // Upload the file.
      request.uploadFile(context, uploadRequestOptions).then((data: request.UploadTask) => {
        data.on(UploadingState.COMPLETE, (result: Array<request.TaskState>) => {
          Logger.info('uploadFile success', JSON.stringify(result));
          if (result && result.length >= 1) {
            serverData.code = Constants.SERVER_CODE_SUCCESS;
            serverData.msg = result[0].message;
            serverData.data = Constants.IMAGE_PREFIX + result[0].path.split('/').pop();
            resolve(serverData);
          }
        });
        data.on(UploadingState.FAIL, (result: Array<request.TaskState>) => {
          Logger.info('uploadFile failed', JSON.stringify(result));
          if (result && result.length >= 1) {
            serverData.msg = $r('app.string.upload_error_message');
            reject(serverData);
          }
        })
      }).catch((err: Error) => {
        Logger.error('uploadFile failed', JSON.stringify(err));
        reject(serverData);
      });
    } catch (err) {
      Logger.error('uploadFile failed', JSON.stringify(err));
      reject(serverData);
    }
  })
}
/*
 *  Copyright (c) 2023 Huawei Device Co., Ltd.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  http://www.apache.org/licenses/LICENSE-2.0
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import { NewsData } from './NewsData';
import ResponseResult from './ResponseResult';
import Constants from '../common/constants/Constants';
import { httpRequestGet, httpRequestPost } from '../common/utils/HttpUtil';
import Logger from '../common/utils/Logger';

class NewsViewModel {
  /**
   * Get news type list from server.
   *
   * @return NewsData[] newsDataList
   */
  getNewsList(currentPage: number, pageSize: number): Promise<NewsData[]> {
    return new Promise(async (resolve: Function, reject: Function) => {
      let url = `${Constants.SERVER}/${Constants.GET_NEWS_LIST}`;
      url += '?currentPage=' + currentPage + '&pageSize=' + pageSize;
      httpRequestGet(url).then((data: ResponseResult) => {
        if (data.code === Constants.SERVER_CODE_SUCCESS) {
          resolve(data.data);
        } else {
          Logger.error('getNewsList failed', JSON.stringify(data));
          reject($r('app.string.page_none_msg'));
        }
      }).catch((err: Error) => {
        Logger.error('getNewsList failed', JSON.stringify(err));
        reject($r('app.string.http_error_message'));
      });
    });
  }

  /**
   * Upload news data.
   *
   * @param newsData
   * @returns NewsData[] newsDataList
   */
  uploadNews(newsData: NewsData): Promise<NewsData[]> {
    return new Promise((resolve: Function, reject: Function) => {
      let url = `${Constants.SERVER}/${Constants.UPLOAD_NEWS}`;
      httpRequestPost(url, newsData).then((result: ResponseResult) => {
        if (result && result.code === Constants.SERVER_CODE_SUCCESS) {
          resolve(result.data);
        } else {
          reject($r('app.string.upload_error_message'));
        }
      }).catch((err: Error) => {
        Logger.error('uploadNews failed', JSON.stringify(err));
        reject($r('app.string.upload_error_message'));
      });
    });
  }
}

let newsViewModel = new NewsViewModel();

export default newsViewModel as NewsViewModel;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2055432.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Java面试八股之消息队列中推模式和拉模式分别有哪些使用场景

消息队列中推模式和拉模式分别有哪些使用场景 消息队列的推模式&#xff08;Push&#xff09;和拉模式&#xff08;Pull&#xff09;各有不同的使用场景和优缺点。下面我会详细介绍这两种模式及其适用场景&#xff1a; 推模式&#xff08;Push&#xff09; 特点&#xff1a;…

进哥在线shinyapps工具(自备)

Jingle’s shinyapps toolkit – 王进的个人网站 (jingege.wang) 一些常用生物信息学分析可视化apps&#xff0c;以及一些分子生物学分析工具&#xff08;尴尬&#xff0c;一直忘记附上链接&#xff09; Jingles toolkit 可以进行多种分析&#xff1a; 1. General plots示例…

putty中修改默认窗口大小和字体、字号

在WinSCP中调用putty&#xff0c;发现默认窗口太小&#xff0c;字号也很小&#xff0c;非常不友好。现在显示器都是1080p起步&#xff0c;所以很有必要修改之。 以中文版v0.70为例&#xff0c;方法&#xff1a; 1. 点击左上角图标 &#xff0c;选择下拉菜单中的“修改设置”&…

Qt-信号和槽(8)

目录 信号的概念 Qt中的信号三要素 connect函数 connect的原型 connect的使用 信号函数和槽函数 参数匹配 close关闭槽函数 运行结果 第一个问题&#xff1a;怎么知道 手册使用 第二个问题&#xff0c;为什么可以直接传递函数指针 自定义槽函数 第一种自定义槽函…

Flask详细教程

1、Flask是什么&#xff1f; Flask是一个非常小的PythonWeb框架&#xff0c;被称为微型框架&#xff08;类似Java的SpringBoot&#xff09;&#xff1b;只提供了一个稳健的核心&#xff0c;其他功能全部是通过扩展实现的&#xff1b;意思就是我们可以根据项目的需要量身定制&a…

前端css动画transform多个属性值写法

X轴平移400px transform: translateX(400px); X轴平移400px并缩小0.5倍 transform: translateX(400px) scale(0.5); X轴平移400px并旋转45度 transform: translateX(400px) rotate(45d…

农产品智慧物流系统pf

TOC springboot537农产品智慧物流系统pf 第1章 绪论 1.1 课题背景 互联网发展至今&#xff0c;无论是其理论还是技术都已经成熟&#xff0c;而且它广泛参与在社会中的方方面面。它让信息都可以通过网络传播&#xff0c;搭配信息管理工具可以很好地为人们提供服务。所以各行…

全新分支版本!微软推出Windows 11 Canary Build 27686版

已经很久没有看到 Windows 11 全新的分支版本了&#xff0c;今天微软发布 Windows 11 Canary 新版本&#xff0c;此次版本号已经转移到 Build 27xxx&#xff0c;首发版本为 Build 27686 版。 此次更新带来了多项改进&#xff0c;包括 Windows Sandbox 沙盒功能切换到 Microsof…

『 Linux 』利用UDP套接字实现简单群聊

文章目录 服务端通过传入命令处理实现远程命令执行使用Windows编辑UDP客户端实现Windows远程控制Linux接收套接字的其他信息UDP套接字简单群聊服务端UDP套接字简单群聊客户端运行测试及分离输入输出 参考代码 服务端通过传入命令处理实现远程命令执行 『 Linux 』利用UDP套接字…

led台灯对眼睛好不好?台灯太亮会影响视力吗?解锁护眼台灯小知识

中国的近视情况十分严峻&#xff0c;尤其在青少年群体中表现得更为突出。据统计&#xff0c;中国青少年的近视率高居世界第一&#xff0c;这主要与长时间的近距离用眼、过度使用电子产品以及户外活动时间减少等因素有关。优质的护眼台灯不仅能减少近视的发生率&#xff0c;还能…

创建一个简单的Vue3.0应用程序

1、Vue.createApp() 方法的介绍 每一个 Vue.js 的应用都需要创建一个应用程序的实例对象并挂载到指定 DOM 上。在 Vue3.0 中&#xff0c;创建一个应用程序实例的语法格式如下&#xff1a; Vue.createApp(App) createApp() 是一个全局 API&#xff0c;它接收一个根组件选项对…

基于SpringBoot+Vue疫情物资捐赠和分配系统--论文pf

TOC springboot518基于SpringBootVue疫情物资捐赠和分配系统--论文pf 第1章 绪论 1.1 课题背景 二十一世纪互联网的出现&#xff0c;改变了几千年以来人们的生活&#xff0c;不仅仅是生活物资的丰富&#xff0c;还有精神层次的丰富。在互联网诞生之前&#xff0c;地域位置往…

开源一款H5自适应留言表白墙php源码下载

开源一款H5自适应留言表白墙php源码下载&#xff0c;优点就是安装简单&#xff0c;功能实用[滑稽][滑稽] 缺点就是UI简陋&#xff0c;功能稀少 第一张是首页&#xff0c;第二张是查看留言 第三张是留言列表(10秒自动刷新)&#xff0c;第四张是表白墙界面

小程序商城被盗刷,使用SCDN安全加速有用吗?

在电子商务蓬勃发展的今天&#xff0c;小程序商城因其便捷性和灵活性成为商家和消费者的新宠。然而&#xff0c;随着其普及&#xff0c;小程序商城的安全问题也日益凸显&#xff0c;尤其是盗刷现象频发&#xff0c;给商家和用户带来了巨大损失。面对这一挑战&#xff0c;是否可…

android13隐藏调节声音进度条下面的设置按钮

总纲 android13 rom 开发总纲说明 目录 1.前言 2.情况分析 3.代码修改 4.编译运行 5.彩蛋 1.前言 将下面的声音调节底下的三个点的设置按钮,隐藏掉。 效果如下 2.情况分析 查看布局文件 通过布局我们可以知道这个按钮就是 com.android.keyguard.AlphaOptimizedImageB…

火语言RPA流程组件介绍--变量赋值

变量赋值 &#x1f6a9;【组件功能】&#xff1a;对已定义的变量进行赋值操作。 支持对任意类型的变量进行赋值&#xff0c;赋值内容可以为字符串也可通过表达式进行计算运行后再赋值给指定变量。 配置预览 配置说明 变量名称 手动输入变量名称或点击输入框下拉选择已创建…

el-form的必填校验的星号*放在label的右边

1.el-form添加hide-required-asterisk <el-form :model"userInfoForm" label-width"80px" :inline"true" :rules"rules" ref"ruleForm"label-position"top"hide-required-asterisk>2.添加样式 .el-form-it…

美国政府紧急应对三星Galaxy手机安全漏洞

一、美国政府紧急通知更新三星Galaxy手机系统 美国政府近日发布紧急通知&#xff0c;要求联邦政府雇员在8月28日前更新三星Galaxy手机系统&#xff0c;否则将面临禁止使用这些设备的后果。这是继7月针对Pixel手机用户的类似要求之后的又一次紧急行动。此次事件的导火索是谷歌发…

Docker-制作镜像

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、操作系统的组成&#xff08;一&#xff09;bootfs&#xff08;二&#xff09;rootfs&#xff08;三&#xff09;Liunx操作系统的启动过程&#xff08;1&…

正确安装振弦式应变的步骤有哪些?

在工程结构监测与评估中&#xff0c;振弦式应变计广泛应用于桥梁、建筑、隧道、大坝等各类结构的健康监测中。它能够实时、准确地反映结构在承受荷载作用下的应变状态&#xff0c;为工程师们提供关键的数据支持&#xff0c;以便及时发现并处理潜在的结构问题。然而&#xff0c;…