download-file.uvue 1.9 KB
Newer Older
1 2 3
<template>
	<view>
		<page-head :title="title"></page-head>
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
4 5
		<view class="uni-padding-wrap uni-common-mt">
			<view v-if="imageSrc" class="image-container">
6 7 8 9 10 11 12 13 14 15 16 17 18 19
				<image class="img" :src="imageSrc" mode="center" />
			</view>
			<view v-else style="margin-top: 50px;">
				<view class="uni-hello-text">
					点击按钮下载服务端示例图片(下载网络文件到本地临时目录)
				</view>
				<view class="uni-btn-v">
					<button type="primary" @tap="downloadImage">下载</button>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
20
	import DownloadTask from 'uts.sdk.modules.DCloudUniNetwork.DownloadTask';
21 22 23 24
	export default {
		data() {
			return {
				title: 'downloadFile',
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
25 26 27
				imageSrc: '',
				task: null as DownloadTask | null,
				pageVisible: false
28 29
			}
		},
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
30 31 32
		onLoad() {
			this.pageVisible = true;
		},
33 34
		onUnload() {
			this.imageSrc = '';
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
35 36 37
			this.pageVisible = false;
			uni.hideLoading();
			this.task?.abort();
38 39
		},
		methods: {
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
40
			downloadImage: function() {
41
				uni.showLoading({
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
42
					title: '下载中'
43 44
				})
				var self = this
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
				this.task = uni.downloadFile({
					url: "https://web-assets.dcloud.net.cn/unidoc/zh/uni-app.png",
					success(res) {
						if (this.pageVisible) {
							console.log('downloadFile success, res is', res)
							self.imageSrc = res.tempFilePath;
							uni.hideLoading();
						}
					},
					fail: (err) => {
						if (this.pageVisible) {
							console.log('downloadFile fail, err is:', err)
							uni.hideLoading();
						}
					}
				});
				this.task?.onProgressUpdate((update) => {
					if (this.pageVisible) {
						console.log("progress : ", update.progress);
					}
65 66 67 68 69 70 71
				})
			}
		}
	}
</script>

<style>
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
72 73 74 75 76 77 78 79 80 81 82 83
	.img {
		width: 500rpx;
		height: 500rpx;
		margin: 0 auto;
	}

	.image-container {
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>