一、微信小程序中的分享
1、分享图片
css
<view class="share-btn" @click="shareToWechat('file')">分享图片</view>
javascript
async shareToWechat(type) {
if (type !== 'file') return;
// this.rptPDF
if (!this.rptPDF) {
uni.showToast({ title: '图片不存在', icon: 'none' });
return;
}
uni.showLoading({ title: '准备分享...' });
// this.rptImgName
uni.downloadFile({
url: this.rptPDF, //下载地址接口返回
success: (data) => {
if (data.statusCode === 200) {
// 2. 弹出和长按完全一样的微信原生分享菜单
wx.showShareImageMenu({
path: data.tempFilePath, // 必须是临时/本地路径
needShowEntrance: true // 分享后带小程序入口(和长按一致)
});
}
},
fail: (err) => {
console.log(err);
uni.showToast({
icon: 'none',
mask: true,
title: '失败请重新下载',
});
},
});
},
2、分享文件、例如pdf
css
<view class="share-btn" @click="previewPdf()">分享文件</view>
javascript
previewPdf() {
if (!this.rptPDF) {
uni.showToast({ title: 'PDF地址异常', icon: 'none' });
return;
}
uni.showLoading({ title: '加载中...' });
uni.downloadFile({
url: this.rptPDF,
success: (res) => {
uni.hideLoading();
if (res.statusCode === 200) {
// 直接发 PDF 文件给微信好友
console.log('res.tempFilePath',res.tempFilePath)
wx.shareFileMessage({
filePath: res.tempFilePath, // 必须是本地临时路径
fileName: '申报单.pdf', // 好友聊天里显示的文件名
success() {
uni.showToast({ title: '分享成功', icon: 'success' });
},
fail(err) {
console.error('分享失败:', err);
uni.showToast({ title: '分享失败', icon: 'none' });
}
});
} else {
uni.showToast({ title: '下载失败', icon: 'none' });
}
},
fail: () => {
uni.hideLoading();
uni.showToast({ title: '网络异常', icon: 'none' });
}
});
},