taro 长按保存照片到系统相册getImageInfo、saveImageToPhotosAlbum
(1)通过长按事件获取到照片路径(或ref获取dom对象)因通e无法获取到src属性,固添加自定义属性为照片url地址<Image className='m-i' data-url={'xx.jpg'} onLongPress={this._LongPress}src='xx.jpg'/>(2)onLongPress长按事件中获取到照片urle.target.dataset.url(3
·
(1)通过长按事件获取到照片路径(或ref获取dom对象)
因通e无法获取到src属性,固添加自定义属性为照片url地址
<Image className='m-i' data-url={'xx.jpg'} onLongPress={this._LongPress} src='xx.jpg'/>
(2)onLongPress长按事件中获取到照片url
e.target.dataset.url
(3)通过Taro.getImageInfo获取到照片的本地路径
Taro.getImageInfo({
src:'图片的路径,可以是相对路径、临时文件路径、存储文件路径、网络图片路径',
success(res)
{
res.path获取到照片的本地路径
}
})
(4)通过Taro.saveImageToPhotosAlbum,将照片保存到系统相册
Taro.saveImageToPhotosAlbum({
filePath:'图片文件路径,可以是临时文件路径或永久文件路径,不支持网络图片路径',
success(res)
{
...
}
})
保存图片底部面报提示、图片授权、以及未授权引导授权、保存成功提示完整代码:
import Taro from '@tarojs/taro'
import {View,Text,Image,OpenData,} from '@tarojs/components'
import React,{Component} from 'react'
import {connect} from 'react-redux'
import './index.less'
import Avator from './child/avator'
import Card from './child/card'
class Mine extends Component{
componentDidMount()
{
}
//长按保存图片到系统相册底部面报提示
_LongPress=(e)=>{
let that=this;
Taro.showActionSheet({
itemList:['保存到系统相册','取消'],
success(res)
{
//保存到系统相册
if(res.tapIndex==0)
{
that._saveImageAuthorize(e.target.dataset.url)
}else{
//取消保存
}
}
})
}
//保存到系统相册授权
_saveImageAuthorize(url)
{
// console.log(url);
let that=this;
Taro.getSetting({
success(res)
{
//未授权
if(!res.authSetting['scope.writePhotosAlbum'])
{
Taro.authorize({
scope: 'scope.writePhotosAlbum',
success: function () {
//同意授权
that._saveImage(url);
},
//拒绝授权引导手动开启
fail()
{
Taro.showModal({
title:'提示',
confirmText:'确认',
cancelText:'取消',
content:'是否开启相册权限',
success(res)
{
if(res.confirm)
{
Taro.openSetting();
}else if(res.cancel)
{
}
}
})
}
})
//已授权
}else{
that._saveImage(url);
}
}
})
}
//将照片保存到系统相册
_saveImage(url)
{
console.log(url);
Taro.getImageInfo({
src:url,
success(res)
{
Taro.saveImageToPhotosAlbum({
filePath:res.path,
success()
{
Taro.showToast({
title:'已保存到系统相册'
})
}
})
}
});
}
render()
{
const {name,avator} = this.props;
return(
<View className='m-c'>
<Image className='m-i' data-url={'https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3213420747,3920605119&fm=26&gp=0.jpg'} onLongPress={this._LongPress} src='https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3213420747,3920605119&fm=26&gp=0.jpg'/>
{/* <OpenData type='userAvatarUrl'/> */}
</View>
)
}
}
const mapStateToProps=(state)=>{
return{
name:state.user.username,
avator:state.user.avator
}
}
export default connect(mapStateToProps)(Mine)
更多推荐
已为社区贡献7条内容
所有评论(0)