上传文件,下载文件 兼容电脑版小程序

由于在手机上操作比较麻烦,现做一个兼容电脑版的上传下载文件;

一、主界面:

1.添加两个按钮

<button size="mini" @click="downFile">下载文件</button>
<button size="mini" @click="selectFile">导入文件</button>

 2、下载文件( 电脑端用剪切板功能复制后去浏览器下载;手机端用小程序的uni.downloadFile 下载)

 downFile(){
       var _this = this
		if(this.platform == 'windows' || this.platform == 'mac'){ //电脑端小程序
			uni.setClipboardData({
				data: `https://xx/xx/file/xx.xlsx`,
				success: function (res) {
					uni.getClipboardData({
					  success: function (res) {}
					})
				}
			})
		} else {
		 uni.downloadFile({
           //代码片段

         });
    }
}

3、导入文件

判断环境,电脑端则跳转到webview界面

            selectFile(){
				var _this = this
				if(this.platform == 'windows' || this.platform == 'mac'){ //电脑端小程序
				   uni.navigateTo({
					  url:'/pages/webview/file'
					})
				} else {
					uni.chooseMessageFile({ // 只适应小程序(电脑端不支持)
						count: 1,
						type: 'file',
						extension: ['xls', 'xlsx'],
						success (result) {
							const tempFilePaths = result.tempFiles
							if (tempFilePaths.length > 0) {
								// 选择文件成功
                                
								}else {
								// 选择文件失败
							}
						}
					})
				  }
                }

 4、监听fileInfo变化,h5中的数据放到主页面中

watch:{
	'$store.state.fileInfo':{
		handler:function(newVal,oldVal){
			this.receiveInfo.push(...newVal)
		},
	}
},
二、webview页面:

单独写一个导入文件功能的h5页面,放到服务器用来嵌入到webview

<view class="content">
	<web-view :src="url" @message="handlePostMessage"></web-view>
</view>
// 嵌入webview的链接
data() {
	return {
		url:'https://xx.cn/ftp/index.html?openId=xxxwwwbbb' 
	}
},
methods: {
	 handlePostMessage(e){
	 //对H5返回的数据做处理
    console.log('e----',e.detail.data[0].res)
       if(res.success){
			const list = res.result
			this.$store.state.fileInfo = list
		} else {
			uni.showToast({
				title: res.message
				icon: 'none',
				duration: 1500
			})
			this.$store.state.fileInfo = []
		}
     }
}

三、h5页面:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>上传文件</title>
        <script
            type="text/javascript"
            src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"
        ></script>
        <script
            type="text/javascript"
            src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"
        ></script>
        <style>
            .btn_group {
                display: flex;
                flex-direction: row;
                justify-content: space-around;
            }
            .choose_container {
                flex: 1;
                padding: 10px 15px;
                border: 1px solid #e4e4e4;
                border-radius: 6px;
                background-color: #fff;
                color: black;
                margin-right: 20px;
            }
            .upload_container {
                flex: 1;
                padding: 10px 15px;
                border: 1px solid #e4e4e4;
                border-radius: 6px;
                background-color: #01b377;
                color: white;
            }
            input[type='file'] {
                display: none;
            }
            #list_container {
                margin: 20px;
            }
        </style>
    </head>
    <body>
        <div class="box_container">
            <input type="file" name="upfile" id="upfile" />
            <div class="btn_group">
                <button class="choose_container">选择文件</button>
                <button class="upload_container">上传文件</button>
            </div>
            <div id="list_container"></div>
        </div>
        <script>
            var openId = window.location.search.split('=')[1];
            // 文件上传后缀
            var suffixList = [
                'doc',
                'docx',
                'xls',
                'xlsx',
                'ppt',
                'pptx',
                'pdf',
            ];
            // 选择文件
            var chooseBtn =document.getElementsByClassName('choose_container')[0];
            var upIpt = document.getElementById('upfile');
            var list = document.getElementById('list_container');
            chooseBtn.addEventListener('click', function () {
                upIpt.click();
            });
            var upFileList;
            upIpt.addEventListener('change', function (res) {
                upFileList = res.target.files;
                if (res.target.files.length > 0) {
                    list.innerText = res.target.files[0].name;
                }
            });
            // 上传文件
            var upBtn = document.getElementsByClassName('upload_container')[0];
            upBtn.addEventListener('click', function () {
                let fileName = upFileList[0].name;
                let lastIndexOf = fileName.lastIndexOf('.') + 1;
                //获取文件的后缀名 txt|...
                let suffix = fileName.substring(lastIndexOf);
                if (suffixList.includes(suffix)) {
                    let fd = new FormData();
                    fd.append('file', upFileList[0]);
										
                    fetch('https://xx.cn/xx/importExcel', {
                        method: 'POST',
                        body: fd,
                        headers: {
							openId: openId
                        },
                    }).then((response) => response.json()).then((res) => {
						wx.miniProgram.postMessage({
							data: {
								res: res,
						},
					});
						wx.miniProgram.navigateBack({ delta: 1 });
					}).catch((err) => {
							console.log('fetch error', err);
					});
                } else {
                    console.log('文件上传格式不符合要求');
                }
            });
        </script>
    </body>
</html>

h5页面原文来自:https://www.cnblogs.com/nicoz/p/16991603.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值