photoAccessHelper
import { fileIo } from '@kit.CoreFileKit' ;
import { photoAccessHelper } from '@kit.MediaLibraryKit' ;
import { bundleManager } from '@kit.AbilityKit' ;
export function getSandboxFiles ( path: string ) {
return ` ${ getContext ( ) . filesDir} / ${ path} ` ;
}
export function getSandboxCache ( path: string ) {
return ` ${ getContext ( ) . cacheDir} / ${ path} ` ;
}
export function addFileFolder ( path: string ) {
fileIo. access ( path, ( err, res: boolean ) => {
if ( ! res) {
fileIo. mkdirSync ( path) ;
}
} )
}
export function copyFileSync ( srcPath: string , destPath: string ) {
const srcFile = fileIo. openSync ( srcPath, fileIo. OpenMode. READ_ONLY ) ;
const destFile = fileIo. openSync ( destPath, fileIo. OpenMode. READ_WRITE | fileIo. OpenMode. CREATE ) ;
fileIo. copyFileSync ( srcFile. fd, destFile. fd) ;
fileIo. closeSync ( srcFile) ;
fileIo. closeSync ( destFile) ;
}
export async function selectImages ( maxNumber: number = 1 , where: string = 'files' ) : Promise < string [ ] > {
if ( where === 'files' ) {
addFileFolder ( getSandboxFiles ( 'images' ) )
}
const photoSelectOptions = new photoAccessHelper . PhotoSelectOptions ( ) ;
photoSelectOptions. MIMEType = photoAccessHelper. PhotoViewMIMETypes. IMAGE_TYPE ;
photoSelectOptions. maxSelectNumber = maxNumber;
const photoViewPicker = new photoAccessHelper . PhotoViewPicker ( ) ;
return photoViewPicker. select ( photoSelectOptions) . then ( ( photoSelectResult: photoAccessHelper. PhotoSelectResult) => {
return photoSelectResult. photoUris. map ( filePath => {
const imageName = filePath. split ( '/' ) . pop ( ) || '' ;
let sandboxPath = ''
if ( where === 'cache' ) {
sandboxPath = getSandboxCache ( imageName) ;
copyFileSync ( filePath, sandboxPath) ;
return sandboxPath;
} else {
sandboxPath = getSandboxFiles ( 'images/' + imageName) ;
copyFileSync ( filePath, sandboxPath) ;
const bundleFlags = bundleManager. BundleFlag. GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION ;
let bundleName = bundleManager. getBundleInfoForSelfSync ( bundleFlags) . name;
return ` file:// ${ bundleName} ${ sandboxPath} ` ;
}
} ) ;
} )
}
使用
import { selectImages } from '../../utils/file' ;
@State tagImage: string = ''
. onClick ( ( ) => {
selectImages ( ) . then ( ( res: string [ ] ) => {
if ( res. length) {
this . tagImage = res[ 0 ]
}
} )
} )
Image ( tagImage)
. width ( 50 )
. height ( 50 )
. borderRadius ( 25 ) ;