uniapp小程序开发-文件预览以及下载保存功能

这个代码Android和iOS都可以适用,代码中已经对iOS环境做了处理。这里的效果图,是以iOS为例进行展示的:

完整代码

页面代码: 

<view style="margin: 10px;">
	文件(点击可下载):
    <view style="color: #1d7fff;" @click="downloadFile">
	      <u-icon name="download" style="margin-right: 8rpx;"></u-icon>测试文件
	</view>
</view>

方法逻辑代码: 

downloadFile() {
	uni.downloadFile({
		url: '你的请求地址',
		header: {
		   'Content-Type': 'multipart/form-data;'
		},
		success: (data) => {
			if (data.statusCode === 200) {
				//隐藏加载框
				uni.hideLoading();
				//文件保存到本地
				uni.saveFile({
					tempFilePath: data.tempFilePath, //临时路径
					success: function(res) {
					    // console.log('打印res',res)
					    uni.showToast({
							icon: 'success',
							mask: true,
							// title: '文件已保存:' + res.savedFilePath, //保存路径
							title: '保存成功',
							duration: 2000,
						});

						//自动打开文档查看
						setTimeout(() => {
							var filePath = res.savedFilePath;
							uni.openDocument({ //新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx。
								filePath: filePath,
								showMenu: true,
								success: function(res) {
									console.log('打开文档成功');
								},
								fail: (e) => {
									console.log(e, '打开失败')
									let nowEno = uni.getSystemInfoSync().platform; //当前环境
									// console.log('===========nowEno', nowEno)
									if (nowEno == 'ios') { //ios打开临时路径文件失败 设置ios环境下读取临时路径文件可以打开
										uni.getFileSystemManager().readFile({
											filePath: filePath,
											success: res => {
												var filebuffer = res.data
												return filebuffer
											},
											fail: err => {
												console.log(err)
												//图片
												uni.saveImageToPhotosAlbum({
												    filePath: filePath,
												    success: res => {
													   uni.showToast({
														title: "成功",
														icon: "none"
													   });
												    },
													fail: err => {
														uni.showToast({
															title: "失败,请稍后重试",
															icon: "none"
														});
													}
										});
								}
							})
						} else {
									uni.showToast({
										title: '打开失败'
									})
								}
							}
						});
				}, 2000)
			}
		});
	}
},
					fail: (err) => {
						console.log(err);
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '文件下载失败',
						});
					},
				});


			}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值