index.html 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport"
  6. content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
  7. <title>选择文件</title>
  8. <style>
  9. .select-file-section {
  10. position: relative;
  11. width: 1px;
  12. height: 1px;
  13. overflow: hidden;
  14. display: inline-block;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="app" class="select-file-section">
  20. <input ref="selectFileRef" :accept="accept" type="file" @change="onChange"></input>
  21. </div>
  22. <script type="text/javascript" src="../js/uni.webview.1.5.5.js"></script>
  23. <script type="text/javascript" src="../js/vue-2.7.14.js"></script>
  24. <script>
  25. let appType = {};
  26. document.addEventListener('UniAppJSBridgeReady', () => {
  27. uni.getEnv(res => {
  28. appType = res;
  29. });
  30. //接受子页面传递过来的消息数据
  31. window.addEventListener('message', (event) => {
  32. if (event.data.source === 'file-web') {
  33. uni.postMessage({
  34. data: event.data
  35. });
  36. }
  37. });
  38. });
  39. //创建vue实例
  40. var app = new Vue({
  41. el: '#app',
  42. data: {
  43. accept: '',
  44. },
  45. mounted() {
  46. let _this = this
  47. this.accept = this.getQueryString('accept');
  48. //接受子页面传递过来的消息数据
  49. window.addEventListener('message', (event) => {
  50. const {
  51. source,
  52. type
  53. } = event.data
  54. if (source === 'file-app' && type === 'selectFile') {
  55. _this.selectFileClick()
  56. }
  57. });
  58. },
  59. methods: {
  60. selectFileClick() {
  61. this.$refs.selectFileRef.click();
  62. },
  63. getQueryString(key) {
  64. let reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)');
  65. let result = window.location.search.substr(1).match(reg);
  66. return result ? decodeURIComponent(result[2]) : null;
  67. },
  68. onChange() {
  69. let fileDom = this.$refs.selectFileRef;
  70. const msgData = {
  71. type: 'selectFileChange',
  72. source: 'file-web',
  73. data: fileDom.files,
  74. }
  75. if (appType.h5) {
  76. window.postMessage(msgData, '*')
  77. } else {
  78. uni.postMessage({
  79. data: msgData
  80. });
  81. }
  82. }
  83. }
  84. })
  85. //选择文件
  86. function selectFile() {
  87. if (appType.h5) {
  88. window.postMessage({
  89. type: 'selectFile',
  90. source: 'file-app',
  91. data: {}
  92. }, '*')
  93. } else {
  94. app.selectFileClick()
  95. }
  96. }
  97. </script>
  98. </body>
  99. </html>