一、获取权限
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; import PreferencesUtil from '../common/utils/PreferencesUtil'; const PERMISSIONS: Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA', 'ohos.permission.CAMERA', 'ohos.permission.INTERNET'] async onCreate(want, launchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); //这里要获取权限 let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager() try { atManager.requestPermissionsFromUser(this.context, PERMISSIONS).then((data) => { AppStorage.SetOrCreate('filePath', this.context.filesDir) AppStorage.SetOrCreate('context', this.context) console.info('appstart'+'MainAbility onCreate') }).catch((err) => { console.info('appstart'+`err: ${JSON.stringify(err)}`) }) } catch (err) { console.info('appstart'+ `catch err->${JSON.stringify(err)}`); } }
二、开发代码
引入资源
import picker from '@ohos.file.picker'; import fs from '@ohos.file.fs'; import util from '@ohos.util'; import image from '@ohos.multimedia.image';
onClick代码
.onClick(() => { let PhotoSelectOptions = new picker.PhotoSelectOptions(); PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; PhotoSelectOptions.maxSelectNumber = 1; let photoPicker = new picker.PhotoViewPicker(); photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => { console.info('uploadImage:' + PhotoSelectResult.photoUris); this.Upload(PhotoSelectResult.photoUris[0]); }).catch((err) => { console.error('uploadImage:PhotoViewPicker.select failed with err: ' + err); }); Upload(userAvatar) { console.log('uploadImage:fileuri:' + userAvatar); fs.open(userAvatar, fs.OpenMode.READ_ONLY).then((file) => { console.info("uploadImage:file fd: " + file.fd); const imageSource = image.createImageSource(file.fd); const imagePackerApi: image.ImagePacker = image.createImagePacker(); let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 30 }; imagePackerApi.packing(imageSource, packOpts).then((readBuffer) => { let bufferArr = new Uint8Array(readBuffer) let help = new util.Base64Helper var base = help.encodeToStringSync(bufferArr) console.info("uploadImage:base is : " + base); //此处进行网络请求,上传到服务器 }); }).catch((err) => { console.info("uploadImage:copy file failed with error message: " + err.message + ", error code: " + err.code); }); }