uniapp通过 WebView 实现跨页面音视频、TXT文件上传与通信

本文基于 UniApp 框架,通过 WebView 嵌入 H5 页面实现文件上传功能,并利用跨页面通信机制将文件地址传回小程序页面。

实现架构

跳转
加载
上传文件
postMessage
uni.$emit
extractCopy.vue
audio.vue/txt.vue
audio.html/txt.html
服务器

核心实现步骤

一、WebView 容器页面

1. audio.vue(音频容器)

<template>
  <web-view @message="handleMessage" :src="`${baseUrl}/audio.html`"></web-view>
</template>

<script>
export default {
      
      
  data() {
      
       return {
      
       baseUrl: '' } },
  methods: {
      
      
    // 接收 H5 页面消息
    handleMessage(e) {
      
      
      const mp3Url = e.detail.data[0].res.data.fullurl
      uni.$emit('mp3UrlReceived', mp3Url) // 触发全局事件
    }
  },
  onLoad() {
      
      
    this.baseUrl = uni.getStorageSync('baseUrl') // 获取基础路径
  }
}
</script>

2. txt.vue(文本容器)

<template>
  <web-view @message="handleMessage" :src="`${baseUrl}/txt.html`"></web-view>
</template>
<!-- 逻辑同 audio.vue,省略 -->

二、H5 上传页面

1. audio.html(音频上传)

<!DOCTYPE html>
<body>
  <input type="file" id="upfile" accept=".mp3" />
  <script>
    document.getElementById('upfile').addEventListener('change', function(e) {
      
      
      const file = e.target.files[0]
      const formData = new FormData()
      formData.append('file', file)

      // 上传文件
      fetch('https://your-api.com/upload', {
      
      
        method: 'POST',
        body: formData
      }).then(res => res.json())
        .then(data => {
      
      
          // 关键通信代码:将结果传回 UniApp
          wx.miniProgram.postMessage({
      
       
            data: {
      
       res: data } 
          })
          wx.miniProgram.navigateBack() // 返回上级页面
        })
    })
  </script>
</body>

运行 HTML

2. txt.html(文本上传)

<!DOCTYPE html>
<body>
  <input type="file" id="fileInput" accept=".txt" />
  <script>
    document.getElementById('fileInput').addEventListener('change', function(e) {
      
      
      const file = e.target.files[0]
      const reader = new FileReader()
      
      reader.onload = function(e) {
      
      
        // 关键通信代码:传递文本内容
        window.postMessage({
      
       
          type: 'uploadSuccess', 
          content: e.target.result 
        })
      }
      reader.readAsText(file)
    })
  </script>
</body>

运行 HTML

三、主页面通信处理

extractCopy.vue(核心片段)

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      mp3Url: '',  // 存储音频地址
      txtContent: '' // 存储文本内容
    }
  },
  onLoad() {
      
      
    // 监听音频地址传递
    uni.$on('mp3UrlReceived', url => {
      
      
      this.mp3Url = url
      this.showUploadUI(false) // 隐藏上传按钮
    })
    
    // 监听文本内容传递
    uni.$on('txtContentReceived', content => {
      
      
      this.txtContent = content
    })
  },
  onUnload() {
      
      
    uni.$off(['mp3UrlReceived', 'txtContentReceived']) // 销毁监听
  },
  methods: {
      
      
    // 跳转到 H5 页面
    navToH5Page(type) {
      
      
      const pathMap = {
      
       
        audio: '/pages/index/audio',
        txt: '/pages/index/txt'
      }
      uni.navigateTo({
      
       url: pathMap[type] })
    }
  }
}
</script>

四、关键机制说明

1. WebView 通信桥梁

  • 通过 wx.miniProgram.postMessage(微信环境)或 window.postMessage 发送数据

  • UniApp 通过 @message 事件接收 H5 页面消息

2. 全局事件总线

  • 使用 uni.$emit uni.$on 实现跨页面通信

  • 避免直接操作父子组件,降低耦合度

3.文件上传要点

  • H5 页面使用原生 触发文件选择

  • FormData 对象处理二进制文件上传

  • 上传成功后立即清理 WebView 页面(navigateBack)

五、注意事项

1. 域名白名单

需在 manifest.json 配置服务器域名白名单,避免出现网络请求拦截

2. H5 页面调试

建议在浏览器中单独调试 H5 页面上传功能,再集成到 WebView

3. 内存管理

页面卸载时务必通过 uni.$off 移除事件监听,防止内存泄漏

4. 跨端兼容

微信环境使用 wx.miniProgram API,其他平台需使用 uni.postMessage

猜你喜欢

转载自blog.csdn.net/weixin_61529967/article/details/145626779
今日推荐