小程序安卓机无法保存图片到相册的问题

58 阅读1分钟

--- theme: juejin

小程序里面ios和安卓的适配性不大相同,IOS可以顺畅保存网络图片(xxx.png) 安卓就不得不做出一些调整了,直接上代码吧

`

 <view class="button-left" @click.stop.prevent="share">分享</view>
        <view class="button-right" @click.stop.prevent="getAuth(e, downLoadFile)">保存至相册</view>
        const getAuth = (e, cb) => {

  wx.getSetting({
    success(res) {
      if (res.authSetting["scope.writePhotosAlbum"]) {
        // 已经获得授权,直接存储
        cb();
      } else if (res.authSetting["scope.writePhotosAlbum"] === undefined) {
        cb();
      } else {
        // 用户拒绝授权后,打开设置页可以看到授权提示开关
        wx.openSetting({
          success(res) {
            // 用户授权
            if (res.authSetting["scope.writePhotosAlbum"]) {
              cb();
            } else {
              // 用户拒绝授权
              wx.showToast({
                title: "权限不足",
              });
            }
          },
          fail(res) {
            wx.showToast({
              title: "设置失败",
            });
          },
        });
      }
    },

    fail(res) {
      console.log(res);
      wx.showToast({
        title: "设置失败",

      });

    },

  });

};

  


const share = () => {
  const fileName = new Date().valueOf();
  const filePath = wx.env.USER_DATA_PATH + "/" + fileName + ".png";
  uni.downloadFile({
    url: props.src,
    filePath: filePath,
    success: (res) => {
      wx.showShareImageMenu({
        path: res.filePath as string,
        success: () => {
          wx.showToast({ title: "分享成功!" });
          wx.reportEvent("gift_share_success");
        },
        fail: (err) => {
          if (err.errMsg === "showShareImageMenu:fail auth deny") {
            askUserToGiveAlbumAuth();
          }
        },
        cancelText: () => {
          wx.showToast({ title: "取消分享" });
        },

      });

    },

  });

};

  


const downLoadFile = () => {

  const fileName = new Date().valueOf();

  const filePath = wx.env.USER_DATA_PATH + "/" + fileName + ".png";

  uni.downloadFile({

    url: props.src,

    filePath: filePath,

    success: (res) => {

      wx.saveImageToPhotosAlbum({

        filePath: res.filePath || "",

        success: () => {

          uni.showToast({

            title: "保存成功",

            icon: "success",

          });

        },

        fail: (err) => {

          console.error("保存图片失败:", err);

        },

      });

    },

  });

};

`