HarmonyOS 用户从APP下载文件到Download目录,正确的流程

下载文件到Download目录,是先去获取download目录还是先去下载文件,在先下载文件到缓存目录之后,复制到Download目录,但是提示copy file failed Operation not permitted,我需要去申请什么权限吗

// 源码如下
Button("文件下载")
  .fontWeight(FontWeight.Bold)
  .onClick(()=>{
    try {
      let uri: string = '';
      // 请确保 getContext(this) 返回结果为 UIAbilityContext
      let context = getContext(this) as common.UIAbilityContext;
      let localFilePath = getContext(this).tempDir + "/test.png"

      request.downloadFile(context, {
        url: 'http://192.168.70.138:7001/downloadFile',
        filePath: localFilePath
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('complete', () => {
          Log.info('download complete');
          const documentViewPicker = new picker.DocumentViewPicker(context);
          const documentSaveOptions = new picker.DocumentSaveOptions();
          documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD;
          documentViewPicker.save(documentSaveOptions ).then((documentSaveResult: Array<string>) => {
            uri = documentSaveResult[0];
            Log.info('路径:' + uri);
            // 将选中文件copy至cache目录下,文件名为cacheFile,这需要ohos.permission.READ_MEDIA与ohos.permission.WRITE_MEDIA权限
            try {
              let srcFile = fs.openSync(localFilePath);
              let dstFile = fs.openSync(uri+  'test.png', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
              fs.copyFileSync(srcFile.fd, dstFile.fd);
              fs.closeSync(srcFile);
              fs.closeSync(dstFile);
            } catch (e) {
              Log.info(`copy file failed ${e.message}`);
              return;
            }

            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}`);
          })

        })
      }).catch((err: BusinessError) => {
        Log.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      Log.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
    }
  })
HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
aquaa

参考:

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

let url ='https://xxx.docx'
let url1 ='https://yyy.png'

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  copyToDownload() {
    let context = getContext() as common.UIAbilityContext;
    let filesDir = context.filesDir;
    let date = new Date();
    let failCallback1 = (err: number) => {
      console.error(`Failed to download the task. Code: ${err}`);
    };
    let fileName = date.getTime() + '.'+ 'png'
    let filePath = filesDir +  '/' + fileName
    try {
      request.downloadFile(context, {
        url: url1,
        filePath: filePath
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('fail', failCallback1);

        downloadTask.on('complete', () => {
          console.info('download complete');
          let documentSaveOptions = new picker.DocumentSaveOptions();
          documentSaveOptions.newFileNames = [fileName];
          let documentPicker = new picker.DocumentViewPicker();
          documentPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
            let uri = documentSaveResult[0];
            let sanFile = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
            let pubFile = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
            fs.copyFileSync(sanFile.fd, pubFile.fd)
            console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' +
            JSON.stringify(documentSaveResult));
          }).catch((err: BusinessError) => {
            console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err));
          });
        })
      }).catch((err: BusinessError) => {
        console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`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.copyToDownload()
        })
    }
    .height('100%')
    .width('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 如何下载文件本地
32浏览 • 1回复 待解决
HarmonyOS 下载文件并保存到指定目录
96浏览 • 1回复 待解决
HarmonyOS下载文件报错
523浏览 • 1回复 待解决
如何查看HarmonyOS下载文件
363浏览 • 1回复 待解决
HarmonyOS下载文件失败返回
511浏览 • 1回复 待解决
是否支持iframe下载文件
806浏览 • 1回复 待解决
如何使用接口下载文件
2124浏览 • 1回复 待解决
HarmonyOS 如何监听下载文件进度
72浏览 • 1回复 待解决
使用request下载文件方式
830浏览 • 1回复 待解决
request下载文件不能覆盖现有文件
1845浏览 • 1回复 待解决
HarmonyOS 使用http下载文件异常
41浏览 • 1回复 待解决
HarmonyOS web下载文件点击无反应
114浏览 • 1回复 待解决
下载文件打印乱码如何修改
387浏览 • 1回复 待解决
HarmonyOS http请求下载文件报错2300023
49浏览 • 1回复 待解决