HarmonyOS 下载操作使用picker.DocumentPickerMode.DOWNLOAD?

创建文件夹并下载,文件创建成功,选择文件夹后无发下载。

代码如下:

import { BusinessError } from '@kit.BasicServicesKit';
import fs, { ListFileOptions, Filter } from '@ohos.file.fs';
import request from '@ohos.request';
import { picker } from '@kit.CoreFileKit';

struct Player {
  @State message: string = 'Hello World';
  @State progress: number = 0;

  download() {
    const context = getContext(this);
    const downloadUrl =
      'xxx.mp4';
    let splitUrl = downloadUrl.split('//')[1].split('/');
    let filePath = splitUrl[splitUrl.length-1];
    console.info('RequestDownload splitUrl:' + splitUrl.toString() + '  filePath:' + filePath.toString())
    try {
      request.downloadFile(context, {
        enableMetered: true,
        url: downloadUrl,
        filePath: context.filesDir + `/${filePath}`
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('fail', (err: number) => {
          console.error(`RequestDownload Failed to download the task. Code: ${err}`);
        });
        downloadTask.on('progress', (receivedSize: number, totalSize: number) => {
          this.progress = Math.floor(receivedSize / totalSize * 100);

          console.log('RequestDownload progress:' + this.progress + ' receivedSize:' + (receivedSize / 1024) +
            ' totalSize:' + (totalSize / 1024));
        });
        downloadTask.on('complete', () => {
          //将文件复制到文件夹中
          const documentSaveOptions = new picker.DocumentSaveOptions(); // 创建文件管理器保存选项实例
          documentSaveOptions.newFileNames = [`${filePath}`]; // 保存文件名(可选)
          // documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD;
          const documentViewPicker = new picker.DocumentViewPicker;
          documentViewPicker.save(documentSaveOptions)
            .then(async (documentSaveResult) => {
              // 获取到到图片或者视频文件的URI后进行文件读取等操作
              let uri = documentSaveResult[0];
              console.info('RequestDownload pub uri:' + uri + ' filePath:' + `/${filePath}`)
              // 沙箱路径文件
              let sanFile = fs.openSync(context.filesDir + `/${filePath}`, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
              let pubFile = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
              console.info(
                'RequestDownload save uri: %s\n' + 'filePath: %s\n' + 'sanFile path: %s\n' +
                  'sanFile name: %s\n' + 'pubFile path: %s\n' + 'pubFile name: %s',
                uri, `/${filePath}`, sanFile.path.toString(), sanFile.name.toString(),
                pubFile.path.toString(), pubFile.name.toString());

              // 将文件从沙箱路拷贝到公共路径
              fs.copyFileSync(sanFile.fd, pubFile.fd)
            })
          console.log('RequestDownload 下载完成')
        })
      }).catch((err: BusinessError) => {
        console.error(`RequestDownload Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`RequestDownload Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
    }
  }

  build() {
    RelativeContainer() {
      Column() {
        // Button('下载')
        // Button($r('app.string.text_download_video_progress', this.progress))
        Button('下载中' + this.progress + '%')
          .onClick(() => {
            this.download()
          })
      }
      .height('100%')
      .width('100%')
      .alignItems(HorizontalAlign.Center)
      .justifyContent(FlexAlign.Center)
    }
  }
}

使用DOWNLOAD就无法正常下载,不使用下载正常。

documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD;
阅读 531
1 个回答

示例参考如下:

import { BusinessError, request } from '@kit.BasicServicesKit';
import { fileUri, picker } from '@kit.CoreFileKit';
import fs from '@ohos.file.fs'

@Entry
@Component
struct Index {
  @State progress: number = 0;
  @State message: string = 'Hello World';

  download() {
    const context = getContext(this);
    const downloadUrl =
      'xxx.mp4';
    let splitUrl = downloadUrl.split('//')[1].split('/');
    let filePath = splitUrl[splitUrl.length-1];
    console.info('RequestDownload splitUrl:' + splitUrl.toString() + '  filePath:' + filePath.toString())
    try {
      request.downloadFile(context, {
        enableMetered: true,
        url: downloadUrl,
        filePath: context.filesDir + `/${filePath}`
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('fail', (err: number) => {
          console.error(`RequestDownload Failed to download the task. Code: ${err}`);
        });
        downloadTask.on('progress', (receivedSize: number, totalSize: number) => {
          this.progress = Math.floor(receivedSize / totalSize * 100);

          console.log('RequestDownload progress:' + this.progress + ' receivedSize:' + (receivedSize / 1024) +
            ' totalSize:' + (totalSize / 1024));
        });
        downloadTask.on('complete', () => {
          const documentViewPicker = new picker.DocumentViewPicker(context);
          const documentSaveOptions = new picker.DocumentSaveOptions();
          documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD;
          documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
            let uri = documentSaveResult[0];
            //拿到uri后需要转换一下
            let path: string = new fileUri.FileUri(uri).path
            let sanFile = fs.openSync(context.filesDir + `/${filePath}`, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
            let pubFile = fs.openSync(path + '/test.mp4', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
            // 将文件从沙箱路拷贝到公共路径
            fs.copyFileSync(sanFile.fd, pubFile.fd)
            console.info('documentViewPicker.save succeed and uri is:' + uri);
          }).catch((err: BusinessError) => {
            console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
          })
          console.log('RequestDownload 下载完成')
        })
      }).catch((err: BusinessError) => {
        console.error(`RequestDownload Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`RequestDownload Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
    }
  }

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          this.download()
        })
    }
    .height('100%')
    .width('100%')
  }
}

保存的文件在手机的文件-\>我的手机-\>下载-\>应用包名文件下。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进