123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport"
- content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
- <title>选择文件</title>
- <style>
- .select-file-section {
- position: relative;
- width: 1px;
- height: 1px;
- overflow: hidden;
- display: inline-block;
- }
- </style>
- </head>
- <body>
- <div id="app" class="select-file-section">
- <input ref="selectFileRef" :accept="accept" type="file" @change="onChange"></input>
- </div>
- <script type="text/javascript" src="../js/uni.webview.1.5.5.js"></script>
- <script type="text/javascript" src="../js/vue-2.7.14.js"></script>
- <script>
- let appType = {};
- document.addEventListener('UniAppJSBridgeReady', () => {
- uni.getEnv(res => {
- appType = res;
- });
- //接受子页面传递过来的消息数据
- window.addEventListener('message', (event) => {
- if (event.data.source === 'file-web') {
- uni.postMessage({
- data: event.data
- });
- }
- });
- });
- //创建vue实例
- var app = new Vue({
- el: '#app',
- data: {
- accept: '',
- },
- mounted() {
- let _this = this
- this.accept = this.getQueryString('accept');
- //接受子页面传递过来的消息数据
- window.addEventListener('message', (event) => {
- const {
- source,
- type
- } = event.data
- if (source === 'file-app' && type === 'selectFile') {
- _this.selectFileClick()
- }
- });
- },
- methods: {
- selectFileClick() {
- this.$refs.selectFileRef.click();
- },
- getQueryString(key) {
- let reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)');
- let result = window.location.search.substr(1).match(reg);
- return result ? decodeURIComponent(result[2]) : null;
- },
- onChange() {
- let fileDom = this.$refs.selectFileRef;
- const msgData = {
- type: 'selectFileChange',
- source: 'file-web',
- data: fileDom.files,
- }
- if (appType.h5) {
- window.postMessage(msgData, '*')
- } else {
- uni.postMessage({
- data: msgData
- });
- }
- }
- }
- })
- //选择文件
- function selectFile() {
- if (appType.h5) {
- window.postMessage({
- type: 'selectFile',
- source: 'file-app',
- data: {}
- }, '*')
- } else {
- app.selectFileClick()
- }
- }
- </script>
- </body>
- </html>
|