ionic2 保存图片到手机相册需要2个原生插件
一、原生插件安装
1、Android Permissions
通过以下命令下载
ionic plugin add cordova-plugin-android-permissions
npm install --save @ionic-native/android-permissions
2、Photo Library
通过以下命令下载
ionic plugin add cordova-plugin-photo-library --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="To choose photos"
npm install --save @ionic-native/photo-library
将以上原生插件引入 app.module.ts 内
import{ PhotoLibrary }from'@ionic-native/photo-library';
import{ AndroidPermissions }from'@ionic-native/android-permissions';
二、在保存图片之前先要确认有没有权限去保存到相册,没有权限的话需要 发送请求去让用户开启权限,然后在保存图片
在组件内引入插件并依赖注入
import{ PhotoLibrary }from'@ionic-native/photo-library';
import{ AndroidPermissions }from'@ionic-native/android-permissions';
constructor(private androidPermissions:AndroidPermissions,private photoLibrary:PhotoLibrary){}
/**
* 保存图片
* @param url 图片路径
*/
saveImage(url:string){
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE).then((result)=>{
if(!result.hasPermission) {
return this.ap.requestPermission(this.ap.PERMISSION.WRITE_EXTERNAL_STORAGE);
}else{
return Promise.resolve({hasPermission:true});
}
}).then((hasPermission)=>{
if(hasPermission){
this.photoLibrary.saveImage(srcUrl,'images').then((res)=>{
console.log(res);
}).catch(e=>{
console.log(e);
});
}else{
this.photoLibrary.saveImage(srcUrl,'images').then((res)=>{
console.log(res);
}).catch(e=>{
console.log(e);
});
}
}).catch(err=>{
this.ap.requestPermission(this.ap.PERMISSION.WRITE_EXTERNAL_STORAGE).then(suc=>{
this.photoLibrary.saveImage(srcUrl,'images').then((res)=>{
console.log(res);
}).catch(e=>{
console.log(e);
});
});
})
}