选择并查看文档与媒体文件
先容
应用使用@ohos.file.picker、@ohos.file.fs等接口,实现了picker拉起文档编辑生存、拉起系统相册图片查看、拉起视频并播放的功能。
效果预览
使用阐明:
- 在首页,应用表现查看最近打开文件功能的跳转按钮,点击后进入文件管理页面,可以通过最近页面,查看最近打开的文件。通过点击右上方的三个按钮,可以分别实现新建文档、选择图片或视频并打开预览、选择文档并打开的功能。
- 在查看文档界面,点击右上方左一按钮,可以实现当前文档另存为的功能;点击右上方中间的按钮,开启文档的编辑功能,textArea变成可编辑状态,用户输入数据后点击右上方第三个按钮,可以将当前文档内容进行生存操作(系统文档没有生存权限)。
- 在查看图片界面,picker拉起系统相册的图片,用户至多可选择三张图片查看,点击图片可以切换所表现的图片名及大小信息。
- 在查看视频界面,picker拉起系统相册的视频,用户至多可选择三个视频查看,点击视频播放并且可以表现的视频名及大小信息。
详细实现
- 拉起picker选择文件、拉起picker生存文件、拉起picker选择图片或视频的功能封装在Index.ets,源码参考:[Index.ets]
- /*
- * Copyright (c) 2024 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 { router } from '@kit.ArkUI';
- import { picker } from '@kit.CoreFileKit';
- import { BusinessError } from '@kit.BasicServicesKit';
- import Logger from '../common/Logger';
- import MediaFileUri from '../media/MediaFileUri';
- import { Constants } from '../common/Constants';
- const MAX_SELECT_NUM = 3; // 选择媒体文件的最大数目
- const TAG = 'pickerIndex';
- @Entry
- @Component
- struct Index {
- @State uri: string = 'Hello World';
- @State filename: string = '';
- @State sizeFile: number = 0;
- @State log: string = '';
- @State imageFlagCur: number = 0;
- @StorageLink('fileSizeList') fileSizeList: Array<number> = [];
- @StorageLink('fileNameList') fileNameList: Array<string> = [];
- @StorageLink('fileUriList') fileUriList: Array<string> = [];
- @StorageLink('imageNames') imageNames: Array<string> = [];
- mediaFileUri: MediaFileUri = new MediaFileUri();
- scroller: Scroller = new Scroller();
- authorizeBundleName: string = 'com.open.file.uri.demo';
- // 拉起picker选择文件
- async callFilePickerSelectFile(): Promise<void> {
- try {
- let DocumentSelectOptions = new picker.DocumentSelectOptions();
- let documentPicker = new picker.DocumentViewPicker();
- documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
- Logger.info(TAG,
- 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
- let editFlag = false;
- if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
- DocumentSelectResult.forEach((value) => {
- this.uri = value;
- editFlag = true;
- Logger.info(TAG, `select file uri: ${this.uri}`);
- })
- }
- if (editFlag) {
- this.getFilenameByUri(this.uri);
- }
- }).catch((err: BusinessError) => {
- Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
- });
- } catch (err) {
- Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
- }
- }
- // 拉起picker保存文件
- async callFilePickerSaveFile(): Promise<void> {
- try {
- let DocumentSaveOptions = new picker.DocumentSaveOptions();
- DocumentSaveOptions.newFileNames = ['MyDocument_01.txt'];
- let documentPicker = new picker.DocumentViewPicker();
- documentPicker.save(DocumentSaveOptions).then((DocumentSaveResult) => {
- Logger.info(TAG,
- 'DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult));
- if (DocumentSaveResult !== null && DocumentSaveResult !== undefined) {
- this.uri = DocumentSaveResult[0];
- Logger.info(TAG, `save file uri: ${this.uri}`);
- }
- this.getFilenameByUri(this.uri);
- }).catch((err: BusinessError) => {
- Logger.error(TAG, 'DocumentViewPicker.save failed with err: ' + JSON.stringify(err));
- });
- } catch (err) {
- Logger.error(TAG, 'DocumentViewPicker failed with err: ' + err);
- }
- }
- async getFilenameByUriForMedia(myUris: string[]) {
- router.pushUrl({
- url: 'pages/ViewMedia',
- params: {
- uris: myUris
- }
- }, router.RouterMode.Standard);
- }
- async getFilenameByUri(myUri: string): Promise<void> {
- // 获取文件名称
- this.filename = (myUri.split('/').pop()) as string;
- router.pushUrl({
- url: 'pages/EditFile',
- params: {
- fileName: this.filename,
- myUri: myUri
- }
- }, router.RouterMode.Standard);
- }
- // 拉起picker选择图片/视频
- async callFilePickerSelectImage(): Promise<void> {
- let array: string[];
- try {
- // 设置photoPicker的参数
- let PhotoSelectOptions = new picker.PhotoSelectOptions();
- // 过滤选择媒体文件类型
- PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE;
- // 选择媒体文件的最大数目
- PhotoSelectOptions.maxSelectNumber = MAX_SELECT_NUM;
- let mediaFlag = false;
- // 使用图库选择器对象前,需要先创建PhotoViewPicker实例
- let photoPicker = new picker.PhotoViewPicker();
- photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
- // 日志中记录成功信息
- Logger.info(TAG,
- 'PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
- // 接口采用callback异步返回形式,返回PhotoSelectResult对象,故进行下一步操作前要先判断是否已经成功返回PhotoSelectResult对象了
- if (PhotoSelectResult !== null && PhotoSelectResult !== undefined) {
- // PhotoSelectResult为返回的结果集。
- // 其中包含Array<string>类型的photoUris,为返回图库选择后的媒体文件的uri数组;还包含boolean类型的isOriginalPhoto,指示返回图库选择后的媒体文件是否为原图。
- // 声明变量array,其取值为PhotoSelectResult中的数组。
- array = PhotoSelectResult['photoUris'];
- array.forEach((value) => {
- this.uri = value;
- mediaFlag = true;
- Logger.info(TAG, `select image/video uri: ${this.uri}`);
- })
- }
- if (mediaFlag) {
- this.getFilenameByUriForMedia(array);
- }
- }).catch((err: BusinessError) => {
- Logger.error(TAG, 'PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
- });
- } catch (err) {
- Logger.error(TAG, 'PhotoViewPicker failed with err: ' + err);
- }
- }
- aboutToDisappear(): void {
- this.fileNameList = [];
- this.fileSizeList = [];
- this.fileUriList = [];
- }
- onPageShow(): void {
- this.mediaFileUri.getAllFiles();
- }
- build() {
- Scroll(this.scroller) {
- Row() {
- Column() {
- Row() {
- Column() {
- Text($r('app.string.last_open'))
- .fontFamily('HarmonyHeiTi-Bold')
- .fontSize($r('app.float.text_font_size_30'))
- .fontWeight(Constants.TEXT_FONT_WIGHT)
- .textAlign(TextAlign.Start)
- .fontColor($r('app.color.text_font_color'))
- .lineHeight($r('app.float.first_line_height'))
- .width(Constants.SEVENTY_PERCENT)
- .height($r('app.float.first_line_height'
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |