溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

微信小程序中如何保存網(wǎng)絡(luò)圖片

發(fā)布時間:2021-03-15 14:59:22 來源:億速云 閱讀:138 作者:小新 欄目:移動開發(fā)

小編給大家分享一下微信小程序中如何保存網(wǎng)絡(luò)圖片,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

該功能需要添加appid才能進(jìn)行正常的測試。

在小程序的文檔中我們得知,wx.saveImageToPhotosAlbum 是用來保存圖片到相冊的。

但是仔細(xì)一看會發(fā)現(xiàn)這個接口的filePath參數(shù)只接受臨時文件路徑或永久文件路徑,不支持網(wǎng)絡(luò)圖片路徑,意味著我們不能直接調(diào)用這個接口。。

因此先需要把該文件下載至本地,使用 wx.downloadFile 。

但值得注意的是小程序只可以跟指定的域名與進(jìn)行網(wǎng)絡(luò)通信,也就是說下載圖片之前,我們需要先去微信公眾者平臺的開發(fā)設(shè)置里設(shè)置uploadFile合法域名。

示例代碼如下:

<!-- index.wxml -->
<image class="qr-code" src="{{url}}" mode="aspectFill" />
<button class="text" bindtap="saveImage">保存圖片</button>
// index.js
const app = getApp()

Page({
  data: {
    url: 'https://avatars3.githubusercontent.com/u/23024075?s=460&v=4'
  },

  // 保存圖片
  saveImage() {
    this.wxToPromise('downloadFile', {
        url: this.data.url
      })
      .then(res => this.wxToPromise('saveImageToPhotosAlbum', {
        filePath: res.tempFilePath
      }))
      .then(res => {
        // do something
        wx.showToast({ title: '保存成功~',icon: 'none' });
      })
      .catch(err) => {
        console.log(err);

        // 如果是用戶自己取消的話保存圖片的話
        // if (~err.errMsg.indexOf('cancel')) return;
      })
  },

  /**
   * 將 callback 轉(zhuǎn)為易讀的 promise
   * @returns [promise]
   */
  wxToPromise(method, opt) {
    return new Promise((resolve, reject) => {
      wx[method]({
        ...opt,
        success(res) {
          opt.success && opt.success();
          resolve(res)
        },
        fail(err) {
          opt.fail && opt.fail();
          reject(err)
        }
      })
    });
  },
})

然后理論上就可以保存圖片了... 用戶第一次在我們的小程序使用保存圖片這個功能是會彈出一個授權(quán)彈框,如果用戶手滑點了拒絕授權(quán)后再點一次保存圖片,然后就會發(fā)現(xiàn)什么反應(yīng)都沒有了。。。

出現(xiàn)這樣的原因是因為這個授權(quán)彈框只會出現(xiàn)一次,所以我們得想辦法再讓用戶重新授權(quán)一次。這時就想到使用 wx.authorize .

但是經(jīng)過測試后發(fā)現(xiàn),使用 wx.authorize 后,會報 authorize:fail auth deny 的錯誤。然后經(jīng)過查閱資料得知:

如果用戶未接受或拒絕過此權(quán)限,會彈窗詢問用戶,用戶點擊同意后方可調(diào)用接口;

如果用戶已授權(quán),可以直接調(diào)用接口;

如果用戶已拒絕授權(quán),則不會出現(xiàn)彈窗,而是直接進(jìn)入接口 fail 回調(diào)。請開發(fā)者兼容用戶拒絕授權(quán)的場景。

emmm... 那這樣效果當(dāng)然不符合我們預(yù)期,只能在換一種方式。這時就想到了使用<button open-type="openSetting"/>,在交互上做一個提示彈框,引導(dǎo)用戶重新授權(quán):

<image class="qr-code" src="{{url}}" mode="aspectFill" />
<button class="text" bindtap="saveImage">保存圖片</button>

<!-- 簡陋版提示 -->
<view wx:if="{{showDialog}}" class="dialog-wrap">
  <view class="dialog">
    這是一段提示用戶授權(quán)的提示語
    <view class="dialog-footer">
      <button
        class="btn"
        open-type="openSetting"
        bindtap="confirm" >
         授權(quán)
      </button>
      <button class="btn" bindtap="cancel">取消</button>
    </view>
  </view>
</view>
const app = getApp()

Page({
  data: {
    url: 'https://avatars3.githubusercontent.com/u/23024075?s=460&v=4',
    showDialog: false,
  },

  saveImage() {
    this.wxToPromise('downloadFile', {
        url: this.data.url
      })
      .then(res => this.wxToPromise('saveImageToPhotosAlbum', {
        filePath: res.tempFilePath
      }))
      .then(res => {
        console.log(res);
        // this.hide();
        wx.showToast({
          title: '保存成功~',
          icon: 'none',
        });
      })
      .catch(({ errMsg }) => {
        console.log(errMsg)
        // if (~errMsg.indexOf('cancel')) return;
        if (!~errMsg.indexOf('auth')) {
          wx.showToast({ title: '圖片保存失敗,稍后再試', icon: 'none' });
        } else {
          // 調(diào)用授權(quán)提示彈框
          this.setData({
            showDialog: true
          })
        };
      })
  },

  // callback to promise
  wxToPromise(method, opt) {
    return new Promise((resolve, reject) => {
      wx[method]({
        ...opt,
        success(res) {
          opt.success && opt.success();
          resolve(res)
        },
        fail(err) {
          opt.fail && opt.fail();
          reject(err)
        }
      })
    });
  },

  confirm() {
    this.setData({
      showDialog:false
    })
  },

  cancel() {
    this.setData({
      showDialog: false
    })
  }
})

最后這樣就完成啦~

看完了這篇文章,相信你對“微信小程序中如何保存網(wǎng)絡(luò)圖片”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI