当前位置:   article > 正文

uniApp下载图片到手机相册,适配Android、Ios、微信小程序、H5_uniapp 下载图片

uniapp 下载图片

1.根据不同设备展示不同的按钮

1.1 图片显示

	<view class="image">
		<image :src="url" mode="widthFix"></image>
	</view>
  • 1
  • 2
  • 3

1.2 微信小程序显示的按钮

	<!-- #ifdef MP-WEIXIN -->
			<view class="uni-flex align-items justify-align-center download backgroundColor" v-if="openSettingBtnHidden"
				@click="saveEwm">下 载</view>
			<button class="uni-flex align-items justify-align-center download backgroundColor" v-else hover-class="none"
				open-type="openSetting" @opensetting="handleSetting">下 载</button>
	<!-- #endif -->
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

1.3 h5显示的按钮

	<!-- #ifdef H5 -->
			<view class="uni-flex align-items justify-align-center btn backgroundColor" @click="saveImgToLocal">下 载
			</view>
	<!-- #endif -->
  • 1
  • 2
  • 3
  • 4

1.4 app显示的按钮

	<!-- #ifdef APP-PLUS -->
	
			<!-- ios按钮 -->
			<button class=" uni-flex align-items justify-align-center  btn backgroundColor" v-if="isIos"
				@click.stop="judgeIosPermission('photoLibrary')">下 载</button>
				
			<!-- Android按钮 -->
			<button class="uni-flex align-items justify-align-center btn backgroundColor" v-if="!isIos"
				@click.stop="requestAndroidPermission('android.permission.WRITE_EXTERNAL_STORAGE')">
				下 载
			</button>
			
	<!-- #endif -->
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2. 引入需要用到的文件

//获取手机相册的访问权限文件
import permision from '@/common/permission.js'
//封装的接口
import Api from '@/api/apply.js'
  • 1
  • 2
  • 3
  • 4

3. data中需要的数据

	data() {
			return {
				url: '',// 下载图片
				openSettingBtnHidden: true, //是否授权
				isIos:false,//判断app系统
			}
		},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

4. onload方法

	// 判断是Android 还是 ios
	
		// #ifdef APP-PLUS
		if (plus.os.name === 'Android') {
			this.isIos = false
		} else {
			this.isIos = true
		}
		// #endif

	//获取接口返回的数据(图片)
		Api.getImage().then(res => {
			if (res.code == 200) {
					this.url = res.data
				}
		})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

5. methods需要用到的方法

			//ios端保存到相册
			judgeIosPermission(permisionID) {
				let _this = this;
				let result = permision.requestIOS(permisionID);
				let strStatus = result ? '已' : '未';
				if (strStatus == '已') {
					if (!uni.getStorageSync('IosPHPhotoLibraryPermission')) {
						uni.showModal({
							content: permisionID + '权限' + strStatus + '获得授权',
							showCancel: false
						});
						uni.setStorageSync('IosPHPhotoLibraryPermission', true);
					}
					_this.saveImgToLocal(_this.url);
				} else {
					uni.showModal({
						content: permisionID + '权限' + strStatus + '获得授权',
						showCancel: false
					});
				}
			},
			//android端保存到相册
			async requestAndroidPermission(permisionID) {
				let _this = this;
				let result = await permision.requestAndroid(permisionID);
				let strStatus;
				if (result == 1) {
					strStatus = '已获得授权';
					if (!uni.getStorageSync('AndroidPHPhotoLibraryPermission')) {
						uni.showModal({
							content: permisionID + strStatus,
							showCancel: false
						});
						uni.setStorageSync('AndroidPHPhotoLibraryPermission', true);
					}
					_this.saveImgToLocal(_this.url);
				} else if (result == 0) {
					strStatus = '未获得授权';
					uni.showModal({
						content: permisionID + strStatus,
						showCancel: false
					});
				} else {
					strStatus = '被永久拒绝权限';
					uni.showModal({
						content: permisionID + strStatus,
						showCancel: false
					});
				}
			},
			//微信小程序保存到相册
			handleSetting(e) {
				if (!e.detail.authSetting['scope.writePhotosAlbum']) {
					this.openSettingBtnHidden = false;
				} else {
					this.openSettingBtnHidden = true;
				}
			},
			saveEwm(e) {
				//获取相册授权
				let _this = this;
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success() {
									_this.saveImgToLocal(_this.url);
								},
								fail() {
									//这里是用户拒绝授权后的回调
									_this.openSettingBtnHidden = false;
								}
							});
						} else {
							//用户已经授权过了
							_this.saveImgToLocal(_this.url);
						}
					}
				});
			},
			saveImgToLocal(e, num) {
				if (num == 1) {
					uni.showModal({
						title: '提示',
						content: '确定保存到相册吗',
						success: res => {
							if (res.confirm) {
								uni.downloadFile({
									url: e.replace('http', 'https'), //图片地址
									success: res => {
										if (res.statusCode === 200) {
											uni.saveImageToPhotosAlbum({
												filePath: res.tempFilePath,
												success: function() {
													uni.showToast({
														title: '保存成功到相册',
														icon: 'none'
													});
												},
												fail: function() {
													uni.showToast({
														title: '保存失败',
														icon: 'none'
													});
												}
											});
										}
									}
								});
							} else if (res.cancel) {}
						}
					});
				} else {
					uni.downloadFile({
						url: e.replace('http', 'https'), //图片地址
						success: res => {
							if (res.statusCode === 200) {
								uni.saveImageToPhotosAlbum({
									filePath: res.tempFilePath,
									success: function() {
										uni.showToast({
											title: '保存成功到相册',
											icon: 'none'
										});
									},
									fail: function() {
										uni.showToast({
											title: '保存失败',
											icon: 'none'
										});
									}
								});
							}
						}
					});
				}
			},
			previewFile() {

				// #ifdef  APP || MP
				uni.downloadFile({
					url: this.url , //后端返回的文件地址
					success: function(res) {
						console.log(res, '下载成功')
						if (res.code === 200) {
							// 打开文件
							uni.saveFile({
								tempFilePath: res.tempFilePath, //临时路径
								success: function(res) {
									uni.showToast({
										icon: 'none',
										mask: true,
										title: '文件已保存:' + res.savedFilePath, //保存路径
										duration: 3000,
									});
									setTimeout(() => {
										//打开文档查看
										uni.openDocument({
											filePath: res.savedFilePath,
											success: function(res) {
												console.log('打开文档成功');
											}
										});
									}, 3000)
								}
							});
						} else {
							uni.showToast({
								title: '打开文件失败请重试',
								icon: 'none'
							})
						}
						uni.hideLoading()
					},
					fail: (err) => {
						uni.hideLoading()
						console.log(err, '下载失败')
						uni.showToast({
							title: '加载失败请重试',
							icon: "none"
						})
					}
				})
				// #endif
			}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186

6. 获取手机相册的访问权限文件

/// null = 未请求,1 = 已允许,0 = 拒绝|受限, 2 = 系统未开启

var isIOS
function album() {
    var result = 0;
    var PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
    var authStatus = PHPhotoLibrary.authorizationStatus();
    if (authStatus === 0) {
        result = null;
    } else if (authStatus == 3) {
        result = 1;
    } else {
        result = 0;
    }
    plus.ios.deleteObject(PHPhotoLibrary);
    return result;
}
function camera() {
    var result = 0;
    var AVCaptureDevice = plus.ios.import("AVCaptureDevice");
    var authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');
    if (authStatus === 0) {
        result = null;
    } else if (authStatus == 3) {
        result = 1;
    } else {
        result = 0;
    }
    plus.ios.deleteObject(AVCaptureDevice);
    return result;
}
function location() {
    var result = 0;
    var cllocationManger = plus.ios.import("CLLocationManager");
    var enable = cllocationManger.locationServicesEnabled();
    var status = cllocationManger.authorizationStatus();
    if (!enable) {
        result = 2;
    } else if (status === 0) {
        result = null;
    } else if (status === 3 || status === 4) {
        result = 1;
    } else {
        result = 0;
    }
    plus.ios.deleteObject(cllocationManger);
    return result;
}
function push() {
    var result = 0;
    var UIApplication = plus.ios.import("UIApplication");
    var app = UIApplication.sharedApplication();
    var enabledTypes = 0;
    if (app.currentUserNotificationSettings) {
        var settings = app.currentUserNotificationSettings();
        enabledTypes = settings.plusGetAttribute("types");
        if (enabledTypes == 0) {
            result = 0;
            console.log("推送权限没有开启");
        } else {
            result = 1;
            console.log("已经开启推送功能!")
        }
        plus.ios.deleteObject(settings);
    } else {
        enabledTypes = app.enabledRemoteNotificationTypes();
        if (enabledTypes == 0) {
            result = 3;
            console.log("推送权限没有开启!");
        } else {
            result = 4;
            console.log("已经开启推送功能!")
        }
    }
    plus.ios.deleteObject(app);
    plus.ios.deleteObject(UIApplication);
    return result;
}
function contact() {
    var result = 0;
    var CNContactStore = plus.ios.import("CNContactStore");
    var cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);
    if (cnAuthStatus === 0) {
        result = null;
    } else if (cnAuthStatus == 3) {
        result = 1;
    } else {
        result = 0;
    }
    plus.ios.deleteObject(CNContactStore);
    return result;
}
function record() {
    var result = null;
    var avaudiosession = plus.ios.import("AVAudioSession");
    var avaudio = avaudiosession.sharedInstance();
    var status = avaudio.recordPermission();
    console.log("permissionStatus:" + status);
    if (status === 1970168948) {
        result = null;
    } else if (status === 1735552628) {
        result = 1;
    } else {
        result = 0;
    }
    plus.ios.deleteObject(avaudiosession);
    return result;
}
function calendar() {
    var result = null;
    var EKEventStore = plus.ios.import("EKEventStore");
    var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0);
    if (ekAuthStatus == 3) {
        result = 1;
        console.log("日历权限已经开启");
    } else {
        console.log("日历权限没有开启");
    }
    plus.ios.deleteObject(EKEventStore);
    return result;
}
function memo() {
    var result = null;
    var EKEventStore = plus.ios.import("EKEventStore");
    var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1);
    if (ekAuthStatus == 3) {
        result = 1;
        console.log("备忘录权限已经开启");
    } else {
        console.log("备忘录权限没有开启");
    }
    plus.ios.deleteObject(EKEventStore);
    return result;
}
function requestIOS(permissionID) {
    return new Promise((resolve, reject) => {
        switch (permissionID) {
            case "push":
                resolve(push());
                break;
            case "location":
                resolve(location());
                break;
            case "record":
                resolve(record());
                break;
            case "camera":
                resolve(camera());
                break;
            case "album":
                resolve(album());
                break;
            case "contact":
                resolve(contact());
                break;
            case "calendar":
                resolve(calendar());
                break;
            case "memo":
                resolve(memo());
                break;
            default:
                resolve(0);
                break;
        }
    });
}
function requestAndroid(permissionID) {
    return new Promise((resolve, reject) => {
        plus.android.requestPermissions(
            [permissionID],
            function(resultObj) {
                var result = 0;
                for (var i = 0; i < resultObj.granted.length; i++) {
                    var grantedPermission = resultObj.granted[i];
                    console.log('已获取的权限:' + grantedPermission);
                    result = 1
                }
                for (var i = 0; i < resultObj.deniedPresent.length; i++) {
                    var deniedPresentPermission = resultObj.deniedPresent[i];
                    console.log('拒绝本次申请的权限:' + deniedPresentPermission);
                    result = 0
                }
                for (var i = 0; i < resultObj.deniedAlways.length; i++) {
                    var deniedAlwaysPermission = resultObj.deniedAlways[i];
                    console.log('永久拒绝申请的权限:' + deniedAlwaysPermission);
                    result = -1
                }
                resolve(result);
            },
            function(error) {
                console.log('result error: ' + error.message)
                resolve({
                    code: error.code,
                    message: error.message
                });
            }
        );
    });
}
function gotoAppPermissionSetting() {
    if (permission.isIOS) {
        var UIApplication = plus.ios.import("UIApplication");
        var application2 = UIApplication.sharedApplication();
        var NSURL2 = plus.ios.import("NSURL");
        var setting2 = NSURL2.URLWithString("app-settings:");
        application2.openURL(setting2);
        plus.ios.deleteObject(setting2);
        plus.ios.deleteObject(NSURL2);
        plus.ios.deleteObject(application2);
    } else {
        var Intent = plus.android.importClass("android.content.Intent");
        var Settings = plus.android.importClass("android.provider.Settings");
        var Uri = plus.android.importClass("android.net.Uri");
        var mainActivity = plus.android.runtimeMainActivity();
        var intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
        intent.setData(uri);
        mainActivity.startActivity(intent);
    }
}
const permission = {
    get isIOS(){
        return typeof isIOS === 'boolean' ? isIOS : (isIOS = uni.getSystemInfoSync().platform === 'ios')
    },
    requestIOS: requestIOS,
    requestAndroid: requestAndroid,
    gotoAppSetting: gotoAppPermissionSetting
}

module.exports = permission

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233

7. 注释:在使用微信小程序的时候,下载需要将域名配置一下白名单,否则没效果哦~~~

最后就可以实现Android、Ios、微信小程序、H5多端下载图片

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/572240
推荐阅读
相关标签
  

闽ICP备14008679号