uni-app 下载文件并保存到手机(带进度条)

编程知识 更新时间:2023-05-02 19:42:01

主要是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”

另外,目前我只在app端亲测可用,其它端待尝试。

更多推荐

uni-app 下载文件并保存到手机(带进度条)

本文发布于:2023-04-28 08:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/ac1431f6e554575a96d4f3cb660257be.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并保存   进度条   文件   手机   uni

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 108160文章数
  • 27359阅读数
  • 0评论数