tt.saveImageToPhotosAlbum
收藏
我的收藏

基础库 1.0.0 开始支持本方法,这是一个异步方法。

保存图片到系统相册。

前提条件
业务背景
使用限制
注意事项
手动取消也会触发失败回调,回调参数为 saveImageToPhotosAlbum:fail cancel,可以通过判断详细错误信息区分取消和其他错误。
支持沙盒
相关教程

语法

tt.saveImageToPhotosAlbum(options)

参数说明

options 为 object 类型,属性如下:

属性名类型默认值必填说明最低支持版本
filePathstring
图片文件路径,可以是临时文件路径,如调用 `tt.downloadFile` 或 `tt.compressImage` 等 API 返回的路径。也可以是永久文件路径,不支持网络路径
1.0.0
successfunction
接口调用成功的回调函数
1.0.0
failfunction
接口调用失败的回调函数
1.0.0
completefunction
接口调用结束的回调函数(调用成功、失败都会执行)
1.0.0

回调成功

object 类型,属性如下:

属性名类型说明最低支持版本
errMsgstring
"saveImageToPhotosAlbum:ok"
1.0.0

回调失败

object 类型,属性如下:

属性名类型说明最低支持版本
errMsgstring
"saveImageToPhotosAlbum:fail" + 详细错误信息
1.0.0

错误码

errNoerrMsg说明最低支持版本
10201"saveImageToPhotosAlbum:fail privacy permission is not authorized"

用户拒绝隐私协议授权,详见小程序隐私协议开发指南

3.19.0
10202"saveImageToPhotosAlbum:fail api scope is not declared in the privacy agreement"

隐私协议中未定义相关隐私信息类型,详见配置隐私协议

3.19.0

扫码体验

请使用字节宿主APP扫码

代码示例

开发者工具中预览

<!-- index.ttml -->
<view class="card-area">
  <image mode="widthFix" src="{{filePath}}" style="width: 300px"></image>
  <button type="primary" bindtap="saveImageToPhotosAlbum">保存</button>
</view>
// index.js
Page({
  data: {
    filePath: "https://s3.pstatp.com/toutiao/static/img/logo.201f80d.png",
  },
  saveImageToPhotosAlbum() {
    tt.downloadFile({
      url: this.data.filePath,
      header: {
        "content-type": "application/json",
      },
      success: (res) => {
        let filePath = res.tempFilePath;
        tt.saveImageToPhotosAlbum({
          filePath, // 暂不支持网络图片/本地图片地址,需与tt.downloadFile一起使用
          success: (res) => {
            tt.showToast({ title: "成功保存到本地相册" });
          },
          fail: (err) => {
            let errType = err.errMsg.includes(
              "saveImageToPhotosAlbum:fail cancel"
            )
              ? "取消保存"
              : "保存失败";
            tt.showModal({
              title: errType,
              content: err.errMsg,
              showCancel: false,
            });
          },
        });
      },
      fail: (err) => {
        tt.showModal({
          title: "下载出错",
          content: err.errMsg,
          showCancel: false,
        });
      },
    });
  },
});