Home  >  Article  >  WeChat Applet  >  Introduction to the method of saving online pictures in WeChat applet (code example)

Introduction to the method of saving online pictures in WeChat applet (code example)

不言
不言forward
2019-02-16 14:04:303849browse

This article brings you an introduction to the method of saving network images in WeChat applet (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This function requires adding appid for normal testing.

In the documentation of the mini program, we learned that wx.saveImageToPhotosAlbum is used to save pictures to the album.

But if you take a closer look, you will find that the filePath parameter of this interface only accepts temporary file paths or permanent file paths, and does not support network image paths, which means that we cannot call this interface directly. .

So you need to download the file locally first, using wx.downloadFile.

But it is worth noting that the mini program can only communicate with the specified domain name. That is to say, before downloading pictures, we need to set the legitimate domain name of uploadFile in the development settings of the WeChat public platform.

The sample code is as follows:

<!-- 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 转为易读的 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)
        }
      })
    });
  },
})

Then theoretically you can save the picture... The first time the user uses the function of saving pictures in our mini program, an authorization pop-up box will pop up. If the user slides and clicks to refuse authorization and then clicks again to save the picture, he or she will find that nothing happens. . .

The reason why this happens is because this authorization pop-up box will only appear once, so we have to find a way to let the user re-authorize again. At this time, I thought of using wx.authorize.

But after testing, I found that after using wx.authorize, the error "authorize:fail auth deny" will be reported. Then after consulting the information, we learned:

If the user has not accepted or rejected this permission, a pop-up window will pop up to ask the user, and the user can only call the interface after clicking to agree;

If the user has authorized , you can call the interface directly;

If the user has refused authorization, the pop-up window will not appear, but the interface fail callback will be entered directly. Developers are asked to be compatible with scenarios where users refuse authorization.

emmm... Of course, the effect is not in line with our expectations, so we can only change it in another way. At this time, I thought of using <button open-type="openSetting"/> to create a prompt pop-up box in the interaction to guide the user to re-authorize:

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

<!-- 简陋版提示 -->
<view wx:if="{{showDialog}}" class="dialog-wrap">
  <view class="dialog">
    这是一段提示用户授权的提示语
    <view class="dialog-footer">
      <button
        class="btn"
        open-type="openSetting"
        bindtap="confirm" >
         授权
      </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 {
          // 调用授权提示弹框
          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
    })
  }
})

Finally, this is it Completed~

Reference for this article: Basic Tutorial on WeChat Mini Program Development https://www.html.cn/study/20.html

The above is the detailed content of Introduction to the method of saving online pictures in WeChat applet (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete