Api:8
语言:js开发
需要权限:
ohos.permission.READ_USER_STORAGE
ohos.permission.WRITE_USER_STORAGE
1.创建项目:
2.示例代码
test.hml
<div class="container">
<button class="title" onclick="getPhotograph">获取图片</button>
<image src="{{ img }}" class="img"></image>
</div>复制
test.css
.container {
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
.title {
font-size: 50px;
padding: 20px 30px;
margin-top: 10px;
}
.img{
width: 500px;
height: 500px;
border: 2px;
margin-top: 10px;
}复制
test.js
import featureAbility from '@ohos.ability.featureAbility';
import Want from '@ohos.application.Want';
export default {
data: {
img:"",
},
// 获取权限,选择图片
getPhotograph(){
let that = this;
let context = featureAbility.getContext();
// let want = Want;
let want = {
"want": {
"deviceId": "",
"bundleName": "",
"abilityName": "",
"uri": "",
"type": "image/*",
"action": "android.intent.action.GET_CONTENT",
"flags":"",
"parameters":{},
"entities":[]
},
};
context.requestPermissionsFromUser(
[
"ohos.permission.READ_USER_STORAGE",
"ohos.permission.WRITE_USER_STORAGE"
], 1, (err, data) => {
if(err){
console.info( "code" + JSON.stringify(err.code));
console.info( "stack" + JSON.stringify(err.stack));
console.info( "message" + JSON.stringify(err.message));
console.info( "name" + JSON.stringify(err.name));
}else{
console.info("authResults==>:" + JSON.stringify(data.authResults));
console.info("permissions==>:" + JSON.stringify(data.permissions));
console.info("requestCode==>:" + JSON.stringify(data.requestCode));
//跳转到相册界面
featureAbility.startAbilityForResult(want, (error, data) => {
if (error) {
console.error('Operation failed. message: ' + error.message);
console.error('Operation failed. name: ' + error.name);
console.error('Operation failed. stack: ' + error.stack);
console.error('Operation failed. code: ' + error.code);
return;
}
if (data.resultCode == -1) { //返回到该界面并且得到了结果
console.info('succeeded: ' + JSON.stringify(data));
console.info('Operation uri: ' + JSON.stringify(data.want.uri));
that.img = data.want.uri
} else { //返回到该界面没有选择相片
console.info('没有选择图片: ');
}
});
}
})
}
}复制
3.效果如图:
4.代码地址
https://gitee.com/jltfcloudcn/jump_to/tree/master/getPhotograph
*附件:js获取相册权限调用相册图片.docx