小程序之點擊下載圖片到本地


話不多說直接上代碼

<template>
    <view class="cart-ticket full-height full-width">
        <!-- 輪播圖 -->
        <swiper v-if="brandList.length > 0" :indicator-dots="true" :autoplay="false" :interval="3000" :duration="1000" 
        class="swiper" indicator-color="#ff9900" indicator-active-color="#ffffff" :current="currentId" @change="swiperChange" >
            <swiper-item v-for="(img, index) in brandList" :key="index" class="swiper-item">
                <image :src="img.posterImg" mode="aspectFill" class="full-height full-width"></image>
            </swiper-item>
        </swiper>
        <button v-if="!isAuthSavePhoto" @tap="onSaveToPhone"  style="background: #294D7C;  
        border-radius: 40upx; text-align: center; color: #ffffff; width: 50%; margin: auto; position: absolute; top: 90%; left: 50%;transform: translate(-50%,-50%);" >
                保存圖片到手機
          </button>
         <button v-if="isAuthSavePhoto" @tap="showModal" style="background: #294D7C;  
        border-radius: 40upx; text-align: center; color: #ffffff;  " >            
              保存圖片到手機
         </button>
    </view>
</template>

<script>
    import couponService from '@/service/CouponService';
    export default {
        components: {
        },
        computed: {
        },
        data() {
            return {
                photoUrl: "https://cz-mall.oss-cn-shenzhen.aliyuncs.com/mall/images/null/20200324/1585041343359vp2.png",
                isAuthSavePhoto: false,
                brandList:[]
            };
        },
        methods: {
            swiperChange(e){
                var index=e.target.current || e.detail.current;
                console.log(index)
                this.photoUrl = this.brandList[index].posterImg
            },
             // 保存圖片到手機
              onSaveToPhone() {
                  if (this.photoUrl.indexOf("https") < 0) {
                      this.photoUrl = this.photoUrl.replace("http:", "https:");
                      
                    }
                    console.log(this.photoUrl)
                this.getSetting().then((res) => {
                  // 判斷用戶是否授權了保存到本地的權限
                  if (!res.authSetting['scope.writePhotosAlbum']) {
                    this.authorize().then(() => {
                      this.savedownloadFile(this.photoUrl)
                      // this.setData({
                      //   isAuthSavePhoto: false
                      // })
                      this.isAuthSavePhoto = false
                    }).catch(() => {
                      wx.showToast({
                        title: '您拒絕了授權',
                        icon: 'none',
                        duration: 1500
                      })
                      this.isAuthSavePhoto = true
                      // this.setData({
                      //   isAuthSavePhoto: true
                      // })
                    })
                  } else {
                    this.savedownloadFile(this.photoUrl)
                  }
                })
              },
              
              
              //打開設置,引導用戶授權
              onOpenSetting() {
                wx.openSetting({
                  success: (res) => {
                    console.log(res.authSetting)
                    if (!res.authSetting['scope.writePhotosAlbum']) {
                      wx.showToast({
                        title: '您未授權',
                        icon: 'none',
                        duration: 1500
                      })
                      
                      this.isAuthSavePhoto =  true
            
                    } else {// 接受授權
                      this.isAuthSavePhoto =  false
                      this.onSaveToPhone() // 接受授權后保存圖片
            
                    }
            
                  }
                })
            
              },
              // 獲取用戶已經授予了哪些權限
              getSetting() {
                return new Promise((resolve, reject) => {
                  wx.getSetting({
                    success: res => {
                      resolve(res)
                    }
                  })
                })
              },
              // 發起首次授權請求
              authorize() {
                return new Promise((resolve, reject) => {
                  wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success: () => {
                      resolve()
                    },
                    fail: res => { //這里是用戶拒絕授權后的回調
                      console.log('拒絕授權')
                      reject()
                    }
                  })
                })
              },
              savedownloadFile(img) {
                        wx.showLoading({
                          title: '保存中...', 
                          mask: true,
                        });
                      
                        wx.downloadFile({
                          url:img,
                          success: function(res) {
                            wx.showToast({
                              title: res,
                              icon: 'success',
                              duration: 2000
                            });
                              console.log(res)
                            if (res.statusCode === 200) {
                              let img = res.tempFilePath;
                              wx.saveImageToPhotosAlbum({
                                filePath: img,
                                success(res) {
                                  wx.showToast({
                                    title: '保存成功',
                                    icon: 'success',
                                    duration: 2000
                                  });
                                },
                                fail(res) {
                                  wx.showToast({
                                    title: '保存失敗',
                                    icon: 'success',
                                    duration: 2000
                                  });
                                }
                              });
                            }
                          }
                        })
                  
                // this.downLoadFile(img).then((res) => {
                //   return this.saveImageToPhotosAlbum(res.tempFilePath)
                // }).then(() => {
                // })
                
                
                
              },
              //單文件下載(下載文件資源到本地),客戶端直接發起一個 HTTPS GET 請求,返回文件的本地臨時路徑。
              downLoadFile(img) {
                return new Promise((resolve, reject) => {
                  wx.downloadFile({
                    url: img,
                    success: (res) => {
                      console.log('downloadfile', res)
                      resolve(res)
                    }
                  })
                })
              },
              // 保存圖片到系統相冊
              saveImageToPhotosAlbum(saveUrl) {
                return new Promise((resolve, reject) => {
                  wx.saveImageToPhotosAlbum({
                    filePath: saveUrl,
                    success: (res) => {
                      wx.showToast({
                        title: '保存成功',
                        duration: 1000,
                      })
                      resolve()
                    }
                  })
                })
              },
              // 彈出模態框提示用戶是否要去設置頁授權
              showModal() {
                wx.showModal({
                  title: '檢測到您沒有打開保存到相冊的權限,是否前往設置打開?',
                  success: (res) => {
                    if (res.confirm) {
                      console.log('用戶點擊確定')
                      this.onOpenSetting() // 打開設置頁面          
                    } else if (res.cancel) {
                      console.log('用戶點擊取消')
                    }
                  }
                })
            },
            loadData() {}
        },
        onLoad(options) {
            // 海報列表
            couponService.getAllPoster({}).then(result => {
                this.brandList = result.list
                this.photoUrl = result.list[0].posterImg
            }).catch(err=> {
                console.log(err)
            });
        }
    };
</script>

<style lang="scss">
    page{
        position: relative;
        width: 100%;
        height: 100%;
        // 輪播圖
        .swiper {
            height: 100%;
            margin: 0upx;
            width: 100%;
            image {
                width: 100%;
            }
        }
        .cart-ticket{
            width: 100%;
            height: 100%;
            background: #ffffff;
        }
        .save_btn{
            font-size: 30rpx;
            line-height: 72rpx;
            color: #fff;
            width:100%;
            height:100%;
            text-align: center;
            border-radius: 36rpx;
            z-index: 10;
            background: #294D7C;
        }
    }
    
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM