小程序保存圖片到本地相冊


  原理:在小程序中先要下載到圖片,在打開本地相冊后保存圖片。

  注意:在小程序后台填寫request合法域名和downloadFile合法域名(因為運用到了下載圖片接口)

  前端代碼如下(非原創):

 1   /**
 2    * 下載圖標到相冊
 3    */
 4   saveToPhone:function(e){
 5     //獲取相冊授權
 6     let imgSrc = this.data.qrcode_img  //要保存的圖片url
 7     console.log(imgSrc)
 8     wx.showLoading({
 9       title: '保存中...'
10     })
11     wx.downloadFile({    //下載文件資源到本地
12       url: imgSrc,
13       success: function (res) {
14         console.log(res);
15         //圖片保存到本地
16         wx.saveImageToPhotosAlbum({
17           filePath: res.tempFilePath,
18           success: function (data) {
19             console.log(data)
20             wx.hideLoading()
21             wx.showToast({
22               title: '保存成功',
23               icon: 'success',
24               duration: 2000
25             })
26           },
27           fail: function (err) {
28             console.log(err);
29             // $yjpToast.show({
30             //   text: `保存失敗`
31             // })
32             if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail:auth denied") {
33               console.log("當初用戶拒絕,再次發起授權")
34               wx.showModal({
35                 title: '提示',
36                 content: '需要您授權保存相冊',
37                 showCancel: false,
38                 success: modalSuccess => {
39                   wx.openSetting({
40                     success(settingdata) {
41                       console.log("settingdata", settingdata)
42                       if (settingdata.authSetting['scope.writePhotosAlbum']) {
43                         wx.showModal({
44                           title: '提示',
45                           content: '獲取權限成功,再次點擊圖片即可保存',
46                           showCancel: false,
47                         })
48                       } else {
49                         wx.showModal({
50                           title: '提示',
51                           content: '獲取權限失敗,將無法保存到相冊哦~',
52                           showCancel: false,
53                         })
54                       }
55                     },
56                     fail(failData) {
57                       console.log("failData", failData)
58                     },
59                     complete(finishData) {
60                       console.log("finishData", finishData)
61                     }
62                   })
63                 }
64               })
65             }
66           },
67           complete(res) {
68             console.log(res);
69             wx.hideLoading()
70           }
71         })
72       }  
73     })
74   },


免責聲明!

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



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