uniapp 下载文件保存到手机

主要是3个步骤
uni.downloadFile:下载文件,获取文件的本地临时路径
uni.saveFile:使用文件的本地临时路径,保存文件到本地,并获取文件的保存路径
uni.openDocument:使用文件的保存路径,打开文件

<template>
	<view>
		<button @tap="downloadFile()">下载</button>
		
		<view class="progress-container" v-if="isShowProgress">
			<view class="progress-box">
				<view class="text">文件下载中,请稍后......</view>
				<progress :percent="progress" show-info stroke-width="3" />
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				url: 'https://xxxxxxxx',
				isShowProgress: false,
				progress: 0,
			}
		},

		methods: {
			downloadFile() {
				const downloadTask = uni.downloadFile({
					url: this.url,
					success: res => {
						if (res.statusCode === 200) {
							this.isShowProgress = false;
							console.log('下载成功');
						}
						let that = this;
						uni.saveFile({
							tempFilePath: res.tempFilePath,
							success: function(red) {
								that.isShowProgress = false;
								uni.showModal({
								    title: '提示',
								    content: '文件已保存:' + red.savedFilePath,
									cancelText: '我知道了',
									confirmText: '打开文件',
								    success: function (res) {
								        if (res.confirm) {
								            uni.openDocument({
								            	filePath: red.savedFilePath,
								            	success: (sus) => {
								            		console.log('成功打开');
								            	}
								            })
								        }
								    }
								});
							}
						});
					}
				})
				
				downloadTask.onProgressUpdate((res) => {
					if(res.progress > 0) {
						this.isShowProgress = true;
					}
					this.progress = res.progress;
					console.log('下载进度:' + res.progress);
					console.log('已下载长度:' + res.totalBytesWritten);
					console.log('文件总长度:' + res.totalBytesExpectedToWrite);
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.progress-container {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99;
		background: rgba(0, 0, 0, .2);
		width: 750rpx;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
		.progress-box {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 30rpx;
			.text {
				margin-bottom: 20rpx;
			}
		}
	}
</style>

注意:虽然能保存到本地,但是保存的位置非常深,不方便用户查找,需要通过文件名搜索去查找
例如:安卓端:“\Android\data\xxxx应用包名\apps\xxxx应用标识\doc\uniapp_save\xxxx”

特别注意:如果无法触发onProgressUpdate,请检查下载地址Response.header是否配置了data-length

posted @ 2023-03-14 16:08  Aaron英语不好  阅读(1000)  评论(0编辑  收藏  举报