123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145 |
- <template>
- </template>
- <script>
- export default {
- data() {
- return {
- imageUrl: 'https://example.com/path/to/your/image.jpg' // 后端提供的图片地址
- };
- },
- methods: {
- // 显示分享菜单
- showShareMenu() {
- uni.showActionSheet({
- itemList: ['下载图片'],
- success: (res) => {
- if (res.tapIndex === 0) {
- this.downloadImage(); // 点击“下载图片”
- }
- }
- });
- },
- // 下载图片
- downloadImage() {
- // #ifdef H5
- this.downloadImageForH5();
- // #endif
- // #ifdef APP-PLUS
- this.downloadImageForApp();
- // #endif
- },
- // H5 环境下载图片
- downloadImageForH5() {
- // 创建一个隐藏的 <a> 标签
- const link = document.createElement('a');
- link.href = this.imageUrl;
- link.download = 'image.jpg'; // 设置下载文件名
- document.body.appendChild(link);
- link.click(); // 触发下载
- document.body.removeChild(link);
- // 提示用户手动保存
- uni.showToast({
- title: '图片已下载,请手动保存到相册。',
- icon: 'none'
- });
- },
- // APP 环境下载图片
- downloadImageForApp() {
- uni.showLoading({
- title: '下载中...',
- mask: true
- });
- // 下载图片
- uni.downloadFile({
- url: this.imageUrl, // 图片地址
- success: (res) => {
- if (res.statusCode === 200) {
- const tempFilePath = res.tempFilePath; // 下载后的临时文件路径
- this.saveImageToAlbum(tempFilePath); // 保存到相册
- } else {
- uni.showToast({
- title: '下载失败',
- icon: 'none'
- });
- }
- },
- fail: (err) => {
- console.error('下载失败:', err);
- uni.showToast({
- title: '下载失败',
- icon: 'none'
- });
- },
- complete: () => {
- uni.hideLoading();
- }
- });
- },
- // 保存图片到相册(APP 环境)
- saveImageToAlbum(tempFilePath) {
- // 检查权限(仅 Android 需要)
- // #ifdef APP-PLUS
- if (uni.getSystemInfoSync().platform === 'android') {
- uni.authorize({
- scope: 'scope.writePhotosAlbum',
- success: () => {
- this.saveImage(tempFilePath);
- },
- fail: () => {
- // 无权限,提示用户去设置
- uni.showModal({
- title: '提示',
- content: '需要相册权限才能保存图片,是否去设置?',
- success: (res) => {
- if (res.confirm) {
- uni.openSetting(); // 打开设置页面
- }
- }
- });
- }
- });
- } else {
- this.saveImage(tempFilePath);
- }
- // #endif
- },
- saveImage(tempFilePath) {
- uni.saveImageToPhotosAlbum({
- filePath: tempFilePath,
- success: () => {
- uni.showToast({
- title: '保存成功',
- icon: 'success'
- });
- },
- fail: (err) => {
- console.error('保存失败:', err);
- uni.showToast({
- title: '保存失败',
- icon: 'none'
- });
- }
- });
- }
- }
- };
- </script>
- <style>
- button {
- margin-top: 20px;
- padding: 10px 20px;
- background-color: #007AFF;
- color: white;
- border-radius: 5px;
- }
- </style>
|