This is the sixth day of my participation in the First Challenge 2022. For details: First Challenge 2022.

preface

Small program received new requirements, need to keep the specified image to the local mobile phone photo albums, using official offer wx. SaveImageToPhotosAlbumapi, can not directly to save, because is filePath can put a temporary file path or permanent file path, but the filePath is a relative path, What we need is either a temporary file path or a permanent file path, so we need to convert it.

Differentiation and development logic

Relative path: Relative file path within the applet project. Temporary file path: Download the generated file from the Internet. Permanent file path: The file path of the file in the applet project.Copy the code

First check whether the permission requested by the user is allowed to save pictures or videos to your album, if not, you should initiate permission application to the user, after the authorization is successful, click Save Picture — > Save success, if rejected, you need to re-authorize through the Settings page

wx.downloadFileandwx.getImageInfo

Wx. downloadFile can only obtain image files from the network, while wx.getImageInfo can obtain both network and local resources.

Wx. downloadFile({url:' network file address ', success: Function (res) {// Fail () {wx.showtoast ({icon: 'none', title: 'save failed, please try again later'}); }})Copy the code

wx.saveImageToPhotosAlbumandwx.downloadFileIn combination with

The saveImageToPhotosAlbum method can be called as long as success corresponds (returning the file path) because it receives a relative path and has the tempFilePath attribute in the callback function. The success and fail methods are used to prompt for successful and failed functions, respectively.

Wx. downloadFile({url:' network file address ', success: function (res) { wx.saveImageToPhotosAlbum({ filePath:res.tempFilePath, success: (res) => { wx.showToast({ title: 'Saved successfully, please view in album'}); }, fail: (err) => {wx.showtoast ({icon: 'none', title: 'save failed, please try again later'}); }})}})Copy the code