upload-file.uvue 2.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
<template>
	<view>
		<page-head :title="title"></page-head>
		<view class="uni-padding-wrap uni-common-mt">
			<view class="demo">
				<image v-if="imageSrc" :src="imageSrc" class="image" mode="widthFix"></image>
				<view v-else class="uni-hello-addfile" @click="chooseImage">+ 选择图片</view>
			</view>
		</view>
	</view>
</template>
<script>
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
13
	import UploadTask from 'uts.sdk.modules.DCloudUniNetwork.UploadTask';
14 15 16 17
	export default {
		data() {
			return {
				title: 'uploadFile',
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
18 19 20
				imageSrc: '',
				task: null as UploadTask | null,
				pageVisible: false
21 22
			}
		},
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
23 24 25
		onLoad() {
			this.pageVisible = true;
		},
26 27
		onUnload() {
			this.imageSrc = '';
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
28 29 30
			this.pageVisible = false;
			uni.hideLoading();
			this.task?.abort();
31 32 33 34 35 36 37 38 39 40
		},
		methods: {
			chooseImage: function() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album'],
					success: (res) => {
						console.log('chooseImage success, temp path is', res.tempFilePaths[0])
						var imageSrc = res.tempFilePaths[0]
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
41 42 43 44 45
						uni.showLoading({
							title: '上传中'
						})
						this.task = uni.uploadFile({
							url: 'https://unidemo.dcloud.net.cn/upload', //仅为示例,非真实的接口地址
46 47 48 49 50 51
							filePath: imageSrc,
							name: 'file',
							formData: {
								'user': 'test'
							},
							success: (res) => {
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
52 53 54 55 56 57 58 59 60 61
								if (this.pageVisible) {
									console.log('uploadImage success, res is:', res)
									uni.hideLoading();
									uni.showToast({
										title: '上传成功',
										icon: 'success',
										duration: 1000
									})
									this.imageSrc = imageSrc
								}
62 63
							},
							fail: (err) => {
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
64 65 66 67 68 69 70 71
								if (this.pageVisible) {
									console.log('uploadImage fail', err);
									uni.hideLoading();
									uni.showModal({
										content: err.errMsg,
										showCancel: false
									});
								}
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
							},
						});
					},
					fail: (err) => {
						console.log('chooseImage fail', err)
					}
				})
			}
		}
	}
</script>

<style>
	.image {
		width: 100%;
	}

	.demo {
		background: #FFF;
		padding: 50rpx;
		justify-content: center;
		align-items: center;
	}

	.uni-hello-addfile {
		text-align: center;
		line-height: 300rpx;
		background: #FFF;
		padding: 50rpx;
		margin-top: 10px;
		font-size: 38rpx;
		color: #808080;
	}
</style>