uni-app小程序下载图片

<view class="bottom">
    <view class="but" v-if="openSettingBtnHidden" @click="saveEwm"><text>保存图片</text></view>
</view>

export default {
   data() {
     return {
       imgurl:'',  // 图片地址
       openSettingBtnHidden: true,  //是否授权

     }

   }

}

// 点击保存图片到相册
        handleSetting(e){
            if (!e.detail.authSetting['scope.writePhotosAlbum']) {
                this.openSettingBtnHidden = false;
            } else {
                this.openSettingBtnHidden = true;
            }
        },
 saveEwm:function(e){
             var that = this
            //获取相册授权
           uni.getSetting({
             success(res) {
               if (!res.authSetting['scope.writePhotosAlbum']) {
                 uni.authorize({
                   scope: 'scope.writePhotosAlbum',
                   success() {
                     //这里是用户同意授权后的回调
                      that.saveImgToLocal(); 
                   },
                   fail() {//这里是用户拒绝授权后的回调
                       this.openSettingBtnHidden=false
                   }
                 })
               } else {//用户已经授权过了
                  that.saveImgToLocal();
               }
             }
           })
        },
        saveImgToLocal:function(e){
            var that = this
            uni.showModal({
                title: '提示',
                content: '确定保存到相册吗',
                success: function (res) {
                    if (res.confirm) {
                        uni.downloadFile({
                                url: that.imgurl,//图片地址
                                success: (res) =>{
                                    if (res.statusCode === 200){
                                        uni.saveImageToPhotosAlbum({
                                            filePath: res.tempFilePath,
                                            success: function() {
                                                uni.showToast({
                                                    title: "保存成功",
                                                    icon: "none"
                                                });
                                            },
                                            fail: function() {
                                                uni.showToast({
                                                    title: "保存失败",
                                                    icon: "none"
                                                });
                                            }
                                        });
                                    } 
                                }
                            })
                    } else if (res.cancel) {
                        
                    }
                }
            });
        },

 

注意:以上代码是我百度的方法,然后根据自己实际的开发需求做了调整,具体是哪位博主的,忘记了,写在这里只是为了给自己记一个笔记,有需要的拿走大家共同学习哈

posted @ 2021-06-16 14:22  温柔本肉  阅读(696)  评论(0编辑  收藏  举报