HarmonyOS 如何下载图片

我写的下载图片方法如下

Prompt.showToast({message: '开始下载'})

let progressCallback1 = (receivedSize: number, totalSize: number) => {
  console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize);
  if(receivedSize == totalSize){
    Prompt.showToast({message: '保存成功'})
    downloadTask.off('progress', progressCallback1);
  }
};

let downloadTask: request.DownloadTask;
console.log(`url: ${url}`);
try {
  request.downloadFile(getContext(), {
    url: url,
    filePath: getContext().filesDir+'/'+url

  }, (err: BusinessError, data: request.DownloadTask) => {
    if (err) {
      console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    downloadTask = data;
    downloadTask.on('progress', progressCallback1);
  });
} catch (err) {
  console.error(`Failed to request the download. err: ${JSON.stringify(err)}`);
}

报错code是13400001 文件操作异常 我在module中已添加了如下权限INTERNET,READ_MEDIA,WRITE_MEDIA,MEDIA_LOCATION

HarmonyOS
9天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

检查测试机网络是否正常联网,测试 demo:

下载图片,并保存至图库

页面:

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

  build() {
    Row() {
      Column() {
        Button('下载文件')
          .onClick(() => {
            downloadFile(getContext(this), "https://agc-storage-drcn.platform.dbankcloud.cn/v0/test-rqcjj/test.png", "tag.png")
          })

        Button('保存图片至图库')
          .onClick(() => {
            saveFromPhotoPicker(getContext(this), "test.png", "tag.png")
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

工具方法:

// 下载文件到沙箱目录
export function downloadFile(ctx: Context, fsUri: string, localPath: string) {
  try {
    request.downloadFile(ctx, {
      url: fsUri,
      filePath: ctx.cacheDir + "/" + localPath // 沙箱路径
    }).then((downloadTask: request.DownloadTask) => {
      downloadTask.on('complete', () => {
        console.info("tag download complete");
      })
    }).catch((err: BusinessError) => {
      console.error("tag invoke download task failed")
    })
  } catch (err) {
    let e = err as BusinessError;
    console.error("tag invoke download file failed, message=" + e.message)
  }
}

// 保存图片到公共目录
export function saveFromPhotoPicker(ctx: Context, pickerFileName: string, localPath: string) {
  let options = new picker.PhotoSaveOptions();
  options.newFileNames = [pickerFileName];
  let p = new picker.PhotoViewPicker();
  let uri: string = "";
  p.save(options).then((res: Array<string>) => {
    // 将文件从沙箱路径拷贝到公共路径
    uri = res[0];
    copyFileToCommon(ctx.cacheDir + "/" + localPath, uri)
    console.info("save to file uri is:", uri)
  })
}
// 拷贝文件,从沙箱拷贝到公共目录
export function copyFileToCommon(src: string, dst: string) {
  try {
    let file = fs.openSync(src, fs.OpenMode.READ_ONLY);
    let file2 = fs.openSync(dst, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); //先创建有读写权限的文件,再把不可读写的文件复制过来
    fs.copyFileSync(file.fd, file2.fd);
  } catch (e) {
    console.error("tag copy error")
  }
}
分享
微博
QQ
微信
回复
8天前
相关问题
HarmonyOS 图片文件下载
210浏览 • 1回复 待解决
HarmonyOS 图片下载相关
91浏览 • 1回复 待解决
HarmonyOS 文件或者图片下载
79浏览 • 1回复 待解决
对指定url的图片进行下载保存
1229浏览 • 1回复 待解决
image组件是否支持图片下载链接
1768浏览 • 1回复 待解决
HarmonyOS 如何下载NDK
746浏览 • 1回复 待解决
下载队列如何干预下载顺序
775浏览 • 1回复 待解决
HarmonyOS smartPerf如何下载使用
914浏览 • 1回复 待解决