百度智能小程序 文件分享到其他App

2020-09-05 14:45 更新

swan.shareFile

在工具和真机中的实现有区别,详见API 实现差异。基础库 3.80.2 开始支持,低版本需做兼容处理。

解释:支持调起系统分享面板将文件分享到其他 App。

Web 态说明:Web 态小程序暂不支持,接口调用会进入失败回调(fail)。

方法参数

Object object

data 参数说明

参数名 类型 是否必填 默认值 说明

filePath

String

需要分享的文档的地址

success

Function

接口调用成功的回调

fail

Function

接口调用失败的回调函数

complete

Function

接口调用结束的回调函数(调用成功、失败都会执行)

示例


图片示例

代码示例 1: 分享本地文件 
在开发者工具中打开

<view class="wrap">
    <button type="primary" bindtap="shareFile">点击分享文件</button>
</view>
Page({
    shareFile() {
        swan.chooseImage({
            count: 1,
            success: res => {
                swan.shareFile({
                    filePath: res.tempFilePaths[0],
                    success: res => {
                        swan.showModal({
                            title: '分享成功',
                            content: JSON.stringify(res)
                        });
                    },
                    fail: err => {
                        swan.showModal({
                            title: '分享失败',
                            content: JSON.stringify(err)
                        });
                    }
                });
            },
            fail: err => {
                swan.showModal({
                    title: '分享失败',
                    content: JSON.stringify(err)
                })
            }
        });
    }
});

代码示例 2: 分享服务器上文件 
在开发者工具中打开

<view class="wrap">
     <view class="card-area">
        <view class="display-area">
            <image class="file-icon" src="/images/file-pdf.png" mode="widthFix"></image>
            <view class="file-label">示例文件.pdf</view>
        </view>
        <button type="primary" bindtap="shareFile">分享服务器上文件</button>
    </view>
</view>
Page({
    shareFile() {
        this.toast('正在保存', 'loading');
        // 不能直接分享网络地址,服务器上的文件需下载到本地
        swan.downloadFile({
            url: 'https://smartprogram.baidu.com/docs/img/file-simple.pdf',
            header: {
                'content-type': 'application/json'
            },
            success: res => {
                const filePath = res.tempFilePath;
                swan.shareFile({
                    filePath,
                    success: res => {
                        swan.showModal({
                            title: '分享成功',
                            content: JSON.stringify(res)
                        });
                    },
                    fail: err => {
                        swan.showModal({
                            title: '分享失败',
                            content: JSON.stringify(err)
                        });
                    }
                });
            },
            fail: err => {
                this.toast('下载文件失败');
            },
            complete: () => {
                swan.hideToast();
            }
        });
    },
    toast(title, icon = 'none') {
        swan.showToast({title, icon});
    }
});


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号