HarmonyOS鸿蒙Next悬赏50积分请把这个ets代码修复一下,让它能正常返回数据

HarmonyOS鸿蒙Next悬赏50积分请把这个ets代码修复一下,让它能正常返回数据

// 图片选择类

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { media } from '@kit.MediaKit';
import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import fs from '@ohos.file.fs';
import dataSharePredicates from '@ohos.data.dataSharePredicates';

const TAG: string = 'ImageSegmentation';

interface photoInfo {
    title?: string
    fiename?: string
    duration?: number
    Path?: string
    Pathurl?: string
    size?: string
    byteSize?: number
    mimeType: 'video' | 'image'
    width?: number
    height?: number
    dateAddedTime?: number
}

interface SelectRes {
    ArryData?: photoInfo[]
}

export class ImagePickerUtil {
    // 使用PhotoPicker选取图片
    static async getUriGallery() { 
        const photoSelectOptions: photoAccessHelper.PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
        photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
        photoSelectOptions.maxSelectNumber = 9;
        const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
        await photoViewPicker.select(photoSelectOptions)
            .then(async (SelectResult: photoAccessHelper.PhotoSelectResult) => {
                let jsonArray: SelectRes[] = [];
                let PhotoFile : Promise<void>[] = []
                const Selecturi = await SelectResult.photoUris
                PhotoFile.push(new Promise(async (resolve) => {
                    for (let i = 0; i < Selecturi.length; i++) {
                        let uri = Selecturi[i];
                        const photoInfo = await ImagePickerUtil.getPhotoInfo(uri)
                        jsonArray.push({ArryData: [{
                                filename: photoInfo.fiename,
                                path: uri,
                                filepath: photoInfo.Pathurl,
                                duration: photoInfo.duration,
                                size: photoInfo.size,
                                byteSize: photoInfo.byteSize,
                                mimeType: photoInfo.mimeType,
                                width: photoInfo.width,
                                height: photoInfo.height,
                                title: photoInfo.title,
                                dateAddedTime: photoInfo.dateAddedTime
                            }
                        ] })
                    }
                })
            )
            })
        return jsonArray;
    }

    static async getPhotoInfo(uri: string): Promise<photoInfo> {
        let context = getContext();
        let tempDir = context.tempDir;
        let photoAccess = photoAccessHelper.getPhotoAccessHelper(context);
        const predicates = new dataSharePredicates.DataSharePredicates()
        predicates.equalTo('uri', uri);
        const fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await photoAccess.getAssets({
                fetchColumns: [
                    photoAccessHelper.PhotoKeys.TITLE,
                    photoAccessHelper.PhotoKeys.DISPLAY_NAME,
                    photoAccessHelper.PhotoKeys.DATE_ADDED_MS,
                    photoAccessHelper.PhotoKeys.DATE_MODIFIED_MS,
                    photoAccessHelper.PhotoKeys.URI,
                    photoAccessHelper.PhotoKeys.PHOTO_TYPE,
                    photoAccessHelper.PhotoKeys.WIDTH,
                    photoAccessHelper.PhotoKeys.HEIGHT,
                    photoAccessHelper.PhotoKeys.SIZE,
                    photoAccessHelper.PhotoKeys.DURATION,
                    photoAccessHelper.PhotoKeys.ORIENTATION
                ],
                predicates,
            } as photoAccessHelper.FetchOptions)
        const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
        const fiename = asset.get(photoAccessHelper.PhotoKeys.DISPLAY_NAME) as string
        const duration = asset.get(photoAccessHelper.PhotoKeys.DURATION) as number
        const title = asset.get(photoAccessHelper.PhotoKeys.TITLE) as string
        const byteSize = asset.get(photoAccessHelper.PhotoKeys.SIZE) as number
        const width = asset.get(photoAccessHelper.PhotoKeys.WIDTH) as number
        const height = asset.get(photoAccessHelper.PhotoKeys.HEIGHT) as number
        const photoType = asset.photoType
        const dateAddedTime = asset.get(photoAccessHelper.PhotoKeys.DATE_ADDED_MS) as number
        let Path = uri
        let tempPath = tempDir + '/'+ fiename
        await ImagePickerUtil.copyFile(uri, tempPath)
        let Pathurl = tempPath
        fetchResult.close()
        await photoAccess.release()
        return {
            fiename,
            Path,
            Pathurl,
            duration,
            size: ImagePickerUtil.formatFileSize(byteSize),
            byteSize,
            width,
            height,
            title,
            mimeType: photoType === photoAccessHelper.PhotoType.VIDEO ? 'video' : 'image',
            dateAddedTime
        } as photoInfo
    }

    static async copyFile(Pathuri: string, tempPath: string) {
        let sourceFile: fs.File | null = null;
        let destFile: fs.File | null = null;
        try {
            sourceFile = fs.openSync(Pathuri, fs.OpenMode.READ_ONLY);
            destFile = fs.openSync(tempPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
            fs.copyFileSync(sourceFile.fd, destFile.fd);
        } catch (err) {
            console.log('err', err.message);
        } finally {
            if (sourceFile) {
                // console.log('sourceFile', sourceFile);
                fs.closeSync(sourceFile);
            }
            if (destFile) {
                // console.log('destFile', destFile);
                fs.closeSync(destFile);
            }
        }
    }

    static formatFileSize(bytes: number): string {
        if (bytes < 1024) {
            return bytes + ' B';
        } else if (bytes < 1024 * 1024) {
            return (bytes / 1024).toFixed(2) + ' KB';
        } else {
            return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
        }
    }
}

希望能正常返回选择后的数据,如:图片uri地址,图片大小,图片沙箱地址这些数据能正常输出。


更多关于HarmonyOS鸿蒙Next悬赏50积分请把这个ets代码修复一下,让它能正常返回数据的实战教程也可以访问 https://www.itying.com/category-93-b0.html

7 回复
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { media } from '@kit.MediaKit';
import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import fs from '@ohos.file.fs';
import dataSharePredicates from '@ohos.data.dataSharePredicates';

const TAG: string = 'ImageSegmentation';

interface photoInfo {
  title?: string
  fiename?: string
  duration?: number
  Path?: string
  Pathurl?: string
  size?: string
  byteSize?: number
  mimeType: 'video' | 'image'
  width?: number
  height?: number
  dateAddedTime?: number
}

interface SelectRes {
  ArryData?: photoInfo[]
}

export class ImagePickerUtil {
  // 使用PhotoPicker选取图片
  static async getUriGallery(): Promise<SelectRes[]> {
    return new Promise((resolve,reject)=>{
      let jsonArray: SelectRes[] = [];

      const photoSelectOptions: photoAccessHelper.PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();

      photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;

      photoSelectOptions.maxSelectNumber = 9;

      const photoViewPicker = new photoAccessHelper.PhotoViewPicker();

      photoViewPicker.select(photoSelectOptions).then((SelectResult: photoAccessHelper.PhotoSelectResult) => {

        let PhotoFile: Promise<void>[] = []

        const Selecturi =  SelectResult.photoUris

        Selecturi.forEach(async (item)=>{
          let url = item
          PhotoFile.push(ImagePickerUtil.getPhotoInfo(url).then((photoInfo)=>{
            if(photoInfo){
              jsonArray.push({
                ArryData: [photoInfo]
              } as SelectRes)
            }
          }))
        })

        Promise.all(PhotoFile).then(()=>{
          resolve(jsonArray)
        })
      })

    })
  }


  static async getPhotoInfo(uri: string): Promise<photoInfo> {

    let context = getContext();

    let tempDir = context.tempDir;

    let photoAccess = photoAccessHelper.getPhotoAccessHelper(context);

    const predicates = new dataSharePredicates.DataSharePredicates()

    predicates.equalTo('uri', uri);

    const fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await photoAccess.getAssets({

      fetchColumns: [

        photoAccessHelper.PhotoKeys.TITLE,

        photoAccessHelper.PhotoKeys.DISPLAY_NAME,

        photoAccessHelper.PhotoKeys.DATE_ADDED_MS,

        photoAccessHelper.PhotoKeys.DATE_MODIFIED_MS,

        photoAccessHelper.PhotoKeys.URI,

        photoAccessHelper.PhotoKeys.PHOTO_TYPE,

        photoAccessHelper.PhotoKeys.WIDTH,

        photoAccessHelper.PhotoKeys.HEIGHT,

        photoAccessHelper.PhotoKeys.SIZE,

        photoAccessHelper.PhotoKeys.DURATION,

        photoAccessHelper.PhotoKeys.ORIENTATION

      ],

      predicates,

    } as photoAccessHelper.FetchOptions)

    const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();

    const fiename = asset.get(photoAccessHelper.PhotoKeys.DISPLAY_NAME) as string

    const duration = asset.get(photoAccessHelper.PhotoKeys.DURATION) as number

    const title = asset.get(photoAccessHelper.PhotoKeys.TITLE) as string

    const byteSize = asset.get(photoAccessHelper.PhotoKeys.SIZE) as number

    const width = asset.get(photoAccessHelper.PhotoKeys.WIDTH) as number

    const height = asset.get(photoAccessHelper.PhotoKeys.HEIGHT) as number

    const photoType = asset.photoType

    const dateAddedTime = asset.get(photoAccessHelper.PhotoKeys.DATE_ADDED_MS) as number

    let Path = uri

    let tempPath = tempDir + '/' + fiename

    await ImagePickerUtil.copyFile(uri, tempPath)

    let Pathurl = tempPath

    fetchResult.close()

    await photoAccess.release()

    return {

      fiename,

      Path,

      Pathurl,

      duration,

      size: ImagePickerUtil.formatFileSize(byteSize),

      byteSize,

      width,

      height,

      title,

      mimeType: photoType === photoAccessHelper.PhotoType.VIDEO ? 'video' : 'image',

      dateAddedTime

    } as photoInfo

  }


  static async copyFile(Pathuri: string, tempPath: string) {

    let sourceFile: fs.File | null = null;

    let destFile: fs.File | null = null;

    try {

      sourceFile = fs.openSync(Pathuri, fs.OpenMode.READ_ONLY);

      destFile = fs.openSync(tempPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);

      fs.copyFileSync(sourceFile.fd, destFile.fd);

    } catch (err) {

      console.log('err', err.message);

    } finally {

      if (sourceFile) {

        // console.log('sourceFile', sourceFile);

        fs.closeSync(sourceFile);

      }

      if (destFile) {

        // console.log('destFile', destFile);

        fs.closeSync(destFile);

      }

    }

  }


  static formatFileSize(bytes: number): string {

    if (bytes < 1024) {

      return bytes + ' B';

    } else if (bytes < 1024 * 1024) {

      return (bytes / 1024).toFixed(2) + ' KB';

    } else {

      return (bytes / (1024 * 1024)).toFixed(2) + ' MB';

    }

  }
}

更多关于HarmonyOS鸿蒙Next悬赏50积分请把这个ets代码修复一下,让它能正常返回数据的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


非常感谢,

对了就是这个数据输出结构能否麻烦您帮我再改下呢,让数据结构简单一些,其他页面好渲染

比如想让输出得到数据结构变成如下模式:

{"ArryData":[

{"fiename":"IMG_091.jpeg","Path":"file://media/Photo/10,"Pathurl":"/data/storage/el2/base/haps/entry/temp/IMG_091.jpeg","duration":0,"size":"554.63KB","byteSize":567937,"width":2519,"height":2519,"title":"IMG_091","mimeType":"image","dateAddedTime":1758602451568},{"fiename":"IMG_092.jpeg","Path":"file://media/Photo/11,"Pathurl":"/data/storage/el2/base/haps/entry/temp/IMG_092.jpeg","duration":0,"size":"554.63KB","byteSize":567937,"width":2519,"height":2519,"title":"IMG_092","mimeType":"image","dateAddedTime":1758602451568},{"fiename":"IMG_093.jpeg","Path":"file://media/Photo/10,"Pathurl":"/data/storage/el2/base/haps/entry/temp/IMG_093.jpeg","duration":0,"size":"554.63KB","byteSize":567937,"width":2519,"height":2519,"title":"IMG_093","mimeType":"image","dateAddedTime":1758602451568}

]}
// 图片选择类

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { media } from '@kit.MediaKit';
import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import fs from '@ohos.file.fs';
import dataSharePredicates from '@ohos.data.dataSharePredicates';

const TAG: string = 'ImageSegmentation';

interface photoInfo {
  title?: string
  fiename?: string
  duration?: number
  Path?: string
  Pathurl?: string
  size?: string
  byteSize?: number
  mimeType: 'video' | 'image'
  width?: number
  height?: number
  dateAddedTime?: number
  filepath?:string
}

interface SelectRes {
  ArryData?: photoInfo[]
}

export class ImagePickerUtil {
  // 使用PhotoPicker选取图片
  static async getUriGallery() {
    const photoSelectOptions: photoAccessHelper.PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    photoSelectOptions.maxSelectNumber = 9;

    const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
    await photoViewPicker.select(photoSelectOptions)
      .then(async (SelectResult: photoAccessHelper.PhotoSelectResult) => {
        let jsonArray: SelectRes[] = [];
        let PhotoFile : Promise<void>[] = []
        const Selecturi = await SelectResult.photoUris

        PhotoFile.push(new Promise(async (resolve) => {
          for (let i = 0; i < Selecturi.length; i++) {
            let uri = Selecturi[i];
            const photoInfo = await ImagePickerUtil.getPhotoInfo(uri)
            jsonArray.push({ArryData: [{
              fiename: photoInfo.fiename,
              Path: uri,
              filepath: photoInfo.Pathurl,
              duration: photoInfo.duration,
              size: photoInfo.size,
              byteSize: photoInfo.byteSize,
              mimeType: photoInfo.mimeType,
              width: photoInfo.width,
              height: photoInfo.height,
              title: photoInfo.title,
              dateAddedTime: photoInfo.dateAddedTime
            }
            ] })
          }
          console.log('jsonArray' + jsonArray[0].ArryData)
          return jsonArray;
        }))
      })
  }

  static async getPhotoInfo(uri: string): Promise<photoInfo> {
    let context = getContext();
    let tempDir = context.tempDir;
    let photoAccess = photoAccessHelper.getPhotoAccessHelper(context);

    const predicates = new dataSharePredicates.DataSharePredicates()
    predicates.equalTo('uri', uri);

    const fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await photoAccess.getAssets({
      fetchColumns: [
        photoAccessHelper.PhotoKeys.TITLE,
        photoAccessHelper.PhotoKeys.DISPLAY_NAME,
        photoAccessHelper.PhotoKeys.DATE_ADDED_MS,
        photoAccessHelper.PhotoKeys.DATE_MODIFIED_MS,
        photoAccessHelper.PhotoKeys.URI,
        photoAccessHelper.PhotoKeys.PHOTO_TYPE,
        photoAccessHelper.PhotoKeys.WIDTH,
        photoAccessHelper.PhotoKeys.HEIGHT,
        photoAccessHelper.PhotoKeys.SIZE,
        photoAccessHelper.PhotoKeys.DURATION,
        photoAccessHelper.PhotoKeys.ORIENTATION
      ],
      predicates,
    } as photoAccessHelper.FetchOptions)

    const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    const fiename = asset.get(photoAccessHelper.PhotoKeys.DISPLAY_NAME) as string
    const duration = asset.get(photoAccessHelper.PhotoKeys.DURATION) as number
    const title = asset.get(photoAccessHelper.PhotoKeys.TITLE) as string
    const byteSize = asset.get(photoAccessHelper.PhotoKeys.SIZE) as number
    const width = asset.get(photoAccessHelper.PhotoKeys.WIDTH) as number
    const height = asset.get(photoAccessHelper.PhotoKeys.HEIGHT) as number
    const photoType = asset.photoType
    const dateAddedTime = asset.get(photoAccessHelper.PhotoKeys.DATE_ADDED_MS) as number

    let Path = uri
    let tempPath = tempDir + '/'+ fiename
    await ImagePickerUtil.copyFile(uri, tempPath)
    let Pathurl = tempPath

    fetchResult.close()
    await photoAccess.release()

    return {
      fiename,
      Path,
      Pathurl,
      duration,
      size: ImagePickerUtil.formatFileSize(byteSize),
      byteSize,
      width,
      height,
      title,
      mimeType: photoType === photoAccessHelper.PhotoType.VIDEO ? 'video' : 'image',
      dateAddedTime
    } as photoInfo
  }

  static async copyFile(Pathuri: string, tempPath: string) {
    let sourceFile: fs.File | null = null;
    let destFile: fs.File | null = null;
    try {
      sourceFile = fs.openSync(Pathuri, fs.OpenMode.READ_ONLY);
      destFile = fs.openSync(tempPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      fs.copyFileSync(sourceFile.fd, destFile.fd);
    } catch (err) {
      console.log('err', err.message);
    } finally {
      if (sourceFile) {
        fs.closeSync(sourceFile);
      }
      if (destFile) {
        fs.closeSync(destFile);
      }
    }
  }

  static formatFileSize(bytes: number): string {
    if (bytes < 1024) {
      return bytes + ' B';
    } else if (bytes < 1024 * 1024) {
      return (bytes / 1024).toFixed(2) + ' KB';
    } else {
      return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
    }
  }
}
export class ImagePickerUtil {
  // 使用PhotoPicker选取图片
  static async getUriGallery(): Promise<SelectRes> {
    return new Promise((resolve,reject)=>{

      const photoSelectOptions: photoAccessHelper.PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();

      photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;

      photoSelectOptions.maxSelectNumber = 9;

      const photoViewPicker = new photoAccessHelper.PhotoViewPicker();

      photoViewPicker.select(photoSelectOptions).then((SelectResult: photoAccessHelper.PhotoSelectResult) => {

        let PhotoFile: Promise<void>[] = []

        const Selecturi =  SelectResult.photoUris
        let ArryData:photoInfo[] = []

        Selecturi.forEach(async (item)=>{
          let url = item
          PhotoFile.push(ImagePickerUtil.getPhotoInfo(url).then((photoInfo)=>{
            if(photoInfo){
              ArryData.push(photoInfo)
            }
          }))
        })

        Promise.all(PhotoFile).then(()=>{
          let jsonArray = {
            ArryData : ArryData
          } as SelectRes
          resolve(jsonArray)
        })
      })

    })
  }

鸿蒙Next中ets代码需使用ArkTS语法。检查数据返回部分是否正确定义了接口类型,确保使用@State@Prop装饰器声明响应式数据。网络请求需使用鸿蒙的http模块,并在aboutToAppear()生命周期中调用。确认返回数据格式与组件绑定的类型一致,避免类型转换错误。

代码存在几个关键问题导致无法正常返回数据:

  1. 异步处理错误:在getUriGallery方法中,Promise数组PhotoFile没有被正确等待,导致返回空数组。

修复后的核心代码:

static async getUriGallery(): Promise<SelectRes[]> {
  const photoSelectOptions: photoAccessHelper.PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  photoSelectOptions.maxSelectNumber = 9;
  
  const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
  const selectResult: photoAccessHelper.PhotoSelectResult = await photoViewPicker.select(photoSelectOptions);
  
  const photoUris = selectResult.photoUris;
  const jsonArray: SelectRes[] = [];

  for (let i = 0; i < photoUris.length; i++) {
    const uri = photoUris[i];
    const photoInfo = await ImagePickerUtil.getPhotoInfo(uri);
    
    jsonArray.push({
      ArryData: [{
        filename: photoInfo.fiename,
        path: uri,
        filepath: photoInfo.Pathurl,
        duration: photoInfo.duration,
        size: photoInfo.size,
        byteSize: photoInfo.byteSize,
        mimeType: photoInfo.mimeType,
        width: photoInfo.width,
        height: photoInfo.height,
        title: photoInfo.title,
        dateAddedTime: photoInfo.dateAddedTime
      }]
    });
  }
  
  return jsonArray;
}
  1. 接口字段名不一致photoInfo接口中定义的是fiename(拼写错误),但使用时是filename,需要统一。

  2. 资源释放时机:在getPhotoInfo中过早释放资源可能导致数据获取不完整。

主要修改点:

  • 移除了不必要的Promise包装
  • 使用同步循环处理多个图片选择
  • 确保所有异步操作都被正确等待
  • 统一了接口字段命名

修复后代码能够正常返回图片的URI地址、文件大小、沙箱路径等数据。

回到顶部