app_u-view实现文件上传和下载预览

<template>
	<view>
		<view>
			<u--image src="../../../../static/workspace/upload.png" width="120rpx" height="120rpx" @click="uploadOpen"></u--image>
			<view class="file-each" v-for="it in filelist" :key="it.fileId" @click="previewFile(it.url)">
				<view>{{it.originalFilename}}</view>
				<view @click.stop="delFile(it)">x</view>
			</view>
			<u-popup :show="isshow" :round="10" @close="close">
				<view class="pop-box">
					<view @click="upSelect(0)" class="w-item">{{columns[0]}}</view>
					<view @click="upSelect(1)" class="w-item" style="border: none;">{{columns[1]}}</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import {
		adminApi
	} from '@/config/index.js'
	import {
		WUpload
	} from '@/utils/upload.js'
	export default {
		props: ['filelist'],
		data() {
			return {
				isshow: false,
				columns: ['文档', '图片']
			}
		},
		methods: {
			delFile(item){
				this.$emit('deleteFile',item.fileId)
			},
			previewFile(url) {
				let that = this;
				uni.showLoading({
					title: '下载中...',
					mask: true
				});
				that.udownload(url, 'temporary')
					.then(path => {
						uni.hideLoading();
						that.uopen(path);
					})
					.catch(() => {
						uni.hideLoading();
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						});
					});
			},
			// 下载临时储存 temporary 临时 local 永久
			udownload(url, type = 'temporary') {
				let that = this;
				return new Promise((resolve, reject) => {
					uni.downloadFile({
						url,
						success: ({ statusCode, tempFilePath }) => {
							if (statusCode === 200) {
								if (type == 'local') {
									uni.saveFile({
										tempFilePath,
										success: ({ savedFilePath }) => that.onCommit(resolve(savedFilePath)),
										fail: () => that.errorHandler('下载失败', reject)
									});
								} else {
									that.onCommit(resolve(tempFilePath));
								}
							}
						},
						fail: () => that.errorHandler('下载失败', reject)
					});
				});
			},
			// 打开文件
			uopen(filePath) {
				let system = uni.getSystemInfoSync().platform;
				if (system == 'ios') {
					filePath = encodeURI(filePath);
				}
				uni.openDocument({
					showMenu: true,
					filePath,
					success: res => {
						console.log('打开文档成功');
					},
					fail: res1 => {
						uni.getImageInfo({
							src: filePath,
							success: imgInfo => {
								uni.previewImage({
									current: filePath,
									urls: [filePath]
								});
							},
							fail: err => {
								uni.showToast({
									title: '不支持该格式',
									icon: 'none'
								});
								return;
							}
						});
					}
				});
			},
			close() {
				this.isshow = false
			},
			uploadOpen() {
				this.isshow = true;
			},
			upSelect(index) {
				if (index == 0) {
					this.upLoadFile();
				} else {
					this.upLoadImg();
				}
				this.isshow = false;
			},
			// 文件上传
			upLoadFile() {
				let that = this;
				uni.chooseFile({
					type: 'file',
					success: function(source) {
						if (source.tempFiles[0].size < 1024 * 1024 * 5) {
							WUpload(
								`${adminApi}/common/upload`,
								'file',
								'Bearer ' + uni.getStorageSync('SET_TOKEN'),
								{},
								source
							).then(res2 => {
								if (res2.code == 200) {
									let Res2 = res2;
									Res2.name = adminApi+res2.fileName
									that.$emit('fileSuccess', Res2); //返回上传成功的数据
									uni.showToast({
										title: '上传成功'
									});
								} else {
									uni.showToast({
										title: '上传失败',
										icon: 'none'
									});
								}
							})
							.catch(catchRes => {
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								});
							});
						} else {
							uni.showToast({
								title: '文件过大,无法上传',
								icon: 'none'
							});
						}
					}
				});
				
			},
			// 图片上传
			upLoadImg(num) {
				let that = this;
				uni.chooseImage({
					count: 1, // 默认9
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
					sourceType: ['camera', 'album'], // 可以指定来源是相册还是相机,默认二者都有
					success: function(source) {
						if (source.tempFiles[0].size < 1024 * 1024 * 2) {
							uni.getImageInfo({
								src: source.tempFilePaths[0],
								success(res) {
									WUpload(
										`${adminApi}/common/upload`,
										'file',
										'Bearer ' + uni.getStorageSync('SET_TOKEN'),
										{},
										source
									)
										.then(res1 => {
											if (res1.code == 200) {
												let Res = res1;
												Res.name = source.tempFilePaths[0];
												if (num == 1) {
													that.$emit('imgSuccess', Res); //返回上传成功的数据
												} else {
													that.$emit('fileSuccess', Res); //返回上传成功的数据
												}
												uni.showToast({
													title: '上传成功'
												});
											} else {
												uni.showToast({
													title: '上传失败',
													icon: 'none'
												});
											}
										})
										.catch(catchRes => {
											console.log(catchRes);
											uni.showToast({
												title: '上传失败',
												icon: 'none'
											});
										});
								},
								fail(error) {
									console.log(error);
								}
							});
						} else {
							uni.showToast({
								title: '图片过大,无法上传',
								icon: 'none'
							});
						}
					}
				});
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	.pop-box{
		height: 250rpx;
		padding: 50rpx 0;
		.w-item{
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-bottom: 1px solid #c3c3c3;
		}
	}
	
	.file-each{
		background-color: #dee2eb;
		margin: 10rpx 0;
		padding: 10rpx 20rpx;
		border-radius: 10rpx ;
		display: flex;
		justify-content: space-between;
		>view:first-child{
			width: 80%;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
.cs 界面代码 using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; public partial class _Default : System.Web.UI.Page { string name="b";//根据需要给上传的图片命名 int minsize=1;//上传文件的最低大小,单位kb int maxsize=1000;//上传文件的最大大小,单位kb protected void Page_Load(object sender, EventArgs e) { } protected void upload_Click(object sender, EventArgs e) { string fileName, fileExtension, FullName; if (UpImage.PostedFile != null) { if (UpImage.PostedFile.ContentLength != 0 && UpImage.PostedFile.ContentLength <= (1024 * maxsize) && UpImage.PostedFile.ContentLength >= (1024 * minsize)) { fileName = System.IO.Path.GetFileName(UpImage.PostedFile.FileName); fileExtension = System.IO.Path.GetExtension(fileName); if (IsExtension(fileExtension)) { try { FullName = name; CreateDir("upLoadImg"); FullName = DateTime.Now.ToString("yyyyMM") + "/" + FullName; UpImage.PostedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath(@"UpFiles/upLoadImg/") + FullName); } catch (Exception ex) { Response.Write("<script language=javascript>alert('" + ex.Message + "');</script>"); } } else { Response.Write("<script language=javascript>alert('上传的文件格式不对,请上传指定的文件格式!');</script>"); } } else { Response.Write("<script language=javascript>alert('没有上传文件,或者文件太大!请重新上传!');</script>"); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SKMA

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值