HarmonyOS Image加载Https图片失败?

使用Image组件加载https://resource.***.com:8443/res/userIcon/38696951721194534820.png

图片加载不成功。该资源在同一手机、同一网络、同一app中使用webview组件可以加载成功,同时在系统浏览器中也可以加载成功。

阅读 441
1 个回答

目前Image就是会受限制,用户可手动用http去下载图片,再用Image去加载即可,具体可参考如下代码:

import rcp from '@hms.collaboration.rcp';
import { common } from '@kit.AbilityKit';
import { JSON } from '@kit.ArkTS';
import fileuri from '@ohos.file.fileuri'
import fileIo from '@ohos.file.fs';

@Entry
@Component
struct Index {
  downloadUrl: string = 'https://resource.***.com:8443/res/userIcon/38696951721194534820.png';
  //设置下载文件生成路径
  context = getContext(this) as common.UIAbilityContext
  @State filePath: string = `${this.context.filesDir}/test3.png`
  @State newPath: string = ''

  build() {
    Column() {
      //文件上传
      Row() {
        Button('下载文件')
          .onClick(() => {
            //下载文件数据
            this.test(this.downloadUrl)
            console.log('---filePath', this.filePath)
            console.log('---newPath', this.newPath)
            setTimeout(()=>{
            },1000)
          })
        Image(this.newPath)
          .width(200)
          .onComplete((msg) => {
            console.log('---图片加载成功', JSON.stringify(msg))
          })
          .onError((msg) => {
            console.log('---图片加载失败', JSON.stringify(msg))
          })
      }
      .margin({ top: 5, bottom: 5 })

    }
    .height('100%')
    .width('100%')

  }

  async test(url: string) {
    // 下载到文件描述符
    const securityConfig: rcp.SecurityConfiguration = {
      remoteValidation: "skip",
    };
    //建立session对象
    let session = rcp.createSession({
      //指定与会话关联的HTTP请求的配置
      requestConfiguration: {
        security: securityConfig
      }
    });
    const respMemory = await session.get(url);
    const dataMemory = respMemory.toString();
    if (fileIo.accessSync(this.filePath)) {
      fileIo.unlinkSync(this.filePath);
    }
    const file = fileIo.openSync(this.filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY);
    const resp = await session.downloadToFile(url, {
      kind: 'file',
      file: file.fd
    });
    this.newPath = fileuri.getUriFromPath(this.filePath)
    fileIo.closeSync(file.fd);
    session.close();
  }
}