/* * 分会活动文件下载 */ import Vue from 'vue'; const _that = new Vue(); export class ActivityFile { static async downloadFile(file_id, file_path, file_type, points) { try { if (points) { // 检查用户积分 const hasEnoughPoints = await this.checkUserPoints(points); if (!hasEnoughPoints) { await this.showPointsNotEnough() return false; } // 显示积分确认弹窗 const confirm = await this.showPointsConfirm(points) if (!confirm) { return false; } } // 执行下载 await this.executeDownload(file_id, file_path, file_type, points) return true; } catch (error) { console.error('下载失败:', error) uni.showToast({ title: '下载失败', icon: 'none' }) return false; } } static async getFilePath(file_id) { return new Promise((resolve) => { _that._get( 'branch.activity/getFilePath', { file_id: file_id, is_original: 1 // 获取原图 }, function(res) { resolve(res.data.file_path); } ); }) } // 检查用户积分 static async checkUserPoints(points) { return new Promise((resolve) => { _that._get( 'branch.activity/checkUserPoints', { points: points }, function(res) { resolve(res.data.is_enough); } ); }) } static async showPointsConfirm(points) { return new Promise((resolve) => { uni.showModal({ title: '下载确认', content: `需要花费${points}个${_that.points_name()},确认下载吗?`, success: (res) => { resolve(res.confirm) } }) }) } static async showPointsNotEnough() { return new Promise((resolve) => { uni.showModal({ title: `${_that.points_name()}不足`, content: `您的${_that.points_name()}不足,无法下载`, showCancel: false, success: resolve }) }) } static async executeDownload(file_id, file_path, file_type = 'image', points) { await uni.showLoading({ title: '下载中,请稍后...' }) // 如果文件路径为空,需要从服务器获取 if (!file_path) { file_path = await this.getFilePath(file_id); } // 生成文件名 const file_name = new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14) + Math.random().toString().slice(2, 6); // #ifdef H5 // 在H5环境中使用Blob方式下载 return await this.downloadViaBlob(file_path, file_name, points); // #endif // #ifdef APP-PLUS || MP-WEIXIN // 在App和微信环境中使用uni.downloadFile return await this.downloadInApp(file_path, points, file_type); // #endif } /** * H5环境下的安全下载 */ static async downloadViaBlob(file_path, file_name, points) { try { const response = await fetch(file_path); const blob = await response.blob(); const objectUrl = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = objectUrl; a.download = file_name; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(objectUrl), 1000); await uni.hideLoading(); // 扣除积分 await this.deductPoints(points); uni.showToast({ title: '下载成功', icon: 'success' }) } catch (error) { await uni.hideLoading(); throw new Error(`下载失败: ${error.message}`); } } static async downloadInApp(file_path, points, file_type) { try { // 下载到临时文件 const downloadResult = await new Promise((resolve, reject) => { uni.downloadFile({ url: file_path, success: (res) => { if (res.statusCode === 200) { resolve(res) } else { reject(new Error(`下载失败,状态码: ${res.statusCode}`)) } }, fail: (err) => reject(err) }) }) const { tempFilePath } = downloadResult // 检查相册权限 const hasPermission = await this.checkPhotoAlbumPermission() if (!hasPermission) { throw new Error('无相册权限') } if (file_type = 'image') { // 保存到相册 await uni.saveImageToPhotosAlbum({ filePath: tempFilePath }) } else { // 保存到相册 await uni.saveVideoToPhotosAlbum({ filePath: tempFilePath }) } await uni.hideLoading(); // 扣除积分 await this.deductPoints(points); uni.showToast({ title: '下载成功', icon: 'success' }); // 清理临时文件 this.cleanTempFile(tempFilePath) } catch (error) { await uni.hideLoading(); throw error } } static async checkPhotoAlbumPermission() { return new Promise((resolve) => { // #ifdef MP-WEIXIN uni.getSetting({ success: (res) => { if (res.authSetting['scope.writePhotosAlbum'] === false) { // 用户之前拒绝过授权 uni.showModal({ title: '需要相册权限', content: '需要您授权相册权限才能保存图片', success: (modalRes) => { if (modalRes.confirm) { uni.openSetting({ success: (settingRes) => { resolve(!!settingRes .authSetting[ 'scope.writePhotosAlbum' ]) }, fail: () => resolve(false) }) } else { resolve(false) } } }) } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) { // 首次申请权限 uni.authorize({ scope: 'scope.writePhotosAlbum', success: () => resolve(true), fail: () => { this.showAuthGuide() resolve(false) } }) } else { // 已有权限 resolve(true) } }, fail: () => resolve(false) }) // #endif // #ifdef APP-PLUS // App端默认有权限或使用原生权限申请 resolve(true) // #endif // #ifdef H5 // H5端不需要相册权限 resolve(true) // #endif }) } static showAuthGuide() { uni.showModal({ title: '权限申请', content: '需要您授权相册权限才能保存图片或视频', success: (res) => { if (res.confirm) { uni.openSetting() } } }) } // 扣除积分 static async deductPoints(points) { return new Promise((resolve) => { _that._get( 'branch.activity/deductPoints', { points: points }, function(res) { resolve(); } ); }) } /** * 清理临时文件 */ static cleanTempFile(tempFilePath) { uni.getFileSystemManager().unlink({ filePath: tempFilePath, fail: (err) => { console.warn('清理临时文件失败:', err) } }) } }