HarmonyOS request下载文件后使用fs.listFileSync无法查找到?

downloadFile(successCallback?: (res: SuccessResult) => void,errorCallback?: (err: ErrorResult) => void,args?:Array<object>){

  let context = getContext(this) as common.UIAbilityContext;
  let filesDir = context.filesDir;
  let url: string = ""
  if(args) {
    url =  args[0]['url']
  }
  if(url == ""){
    //todo 错误提示
  }
  try {
    request.downloadFile(context, {
      url: url,
      filePath: filesDir+"test.doc"
    }).then((downloadTask) => {
      downloadTask.on('complete', () => {
        console.info('download complete');
        //todo 下载成功
      })
    }).catch((err:object)=>{
    })
  } catch (err) {
    console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
  }
  this.viewFileList()
}
viewFileList(){
  let context = getContext(this) as common.UIAbilityContext;
  let filesDir = context.filesDir;
  let listFileOption: ListFileOptions = {
    recursion: false,
    listNum: 0,
  };
  let filenames = fs.listFileSync(filesDir, listFileOption);
  console.info("listFile succeed");
  for (let i = 0; i < filenames.length; i++) {
    console.info("filename: %s", filenames[i]);
  }
}

上面是下载和查看方法,但是查找文件始终是空的,请问应该如何修改,才能查找到刚刚下载的文件。

阅读 406
1 个回答

是否做了异步处理?不做异步处理的话,打开的文件列表是会为空的,因为文件还未下载完成。

示例代码如下:

let downloadTask;
try {
  request.downloadFile(context, {
    url : url,
    filePath: filePath
  }).then((downloadTask:request.DownloadTask)=>{
    downloadTask.on('complete',()=>{
      console.info('download complete');
      let file = fs.openSync(filePath,fs.OpenMode.READ_WRITE);
      let arrayBuffer = new ArrayBuffer(1024);
      let readLen = fs.readSync(file.fd, arrayBuffer);
      let buf = buffer.from(arrayBuffer,0,readLen);
      console.info(`content of File: ${buf.toString()}`);
      fs.closeSync(file);
      //读取文件
      this.viewFileList()
    })
  }).catch((err:BusinessError)=>{
    console.error(`downLoadFileTask failed, code is ${err.code}, message is ${err.message}`);
  });
} catch (error){
  console.error(`downLoadFileTask failed, code is ${error.code}, message is ${error.message}`);
}

将读取文件的代码放在了写入文件后面,是可以读取到的,需要做异步处理。

logo
HarmonyOS
子站问答
访问
宣传栏