QUICK_START.md 6.1 KB

快速开始指南

5 分钟上手 UploadManager

1. 基本上传

import getUploadManager from '@/utils/uploadManager'

const uploadManager = getUploadManager()

// 上传文件
const url = await uploadManager.upload(
  {
    path: 'file:///storage/audio.mp3',
    name: 'audio.mp3',
    size: 1024000
  },
  {
    onProgress: (percent) => console.log(`${percent}%`),
    onSuccess: (url) => console.log(url),
    onFailure: (error) => console.error(error)
  }
)

2. 错误处理

try {
  await uploadManager.upload(file, options)
} catch (error) {
  if (error.message.includes('未就绪')) {
    // 策略未就绪,稍后重试
    uni.showToast({ title: '初始化中,请稍后重试', icon: 'none' })
  } else {
    // 其他错误
    uni.showToast({ title: `上传失败: ${error.message}`, icon: 'none' })
  }
}

3. 切换策略

// 使用 Native 策略(高性能)
uploadManager.setStrategy('native')

// 使用 UniApp 策略(推荐)
uploadManager.setStrategy('uniapp')

// 使用 WebView 策略(兜底)
uploadManager.setStrategy('webview')

4. WebView 策略初始化

<template>
  <web-view 
    ref="uploaderWebview" 
    src="/hybrid/html/index.html" 
    @message="handleUploadMessage"
  />
</template>

<script>
export default {
  methods: {
    handleUploadMessage(event) {
      const data = event.detail.data[0]

      // 初始化 WebView 策略
      if (data?.action === 'webview_ready') {
        this.$nextTick(() => {
          this.uploadManager.initializeWebViewStrategy(
            this.$refs.uploaderWebview,
            this
          )
        })
      }

      // 处理上传回调
      this.uploadManager.handleWebViewMessage(event)
    }
  }
}
</script>

5. 配置管理

// 更新配置
await uploadManager.updateConfig({
  preferredStrategy: 'native',
  strategyPriority: ['native', 'uniapp', 'webview'],
  retryConfig: {
    maxRetries: 3,
    retryDelay: 1000
  }
})

// 获取当前配置
const config = uploadManager.getConfig()

6. 取消上传

// 开始上传
const uploadPromise = uploadManager.upload(file, options)

// 取消上传
uploadManager.cancel()

常见场景

场景 1: 录音上传

import getUploadManager from '@/utils/uploadManager'

export default {
  methods: {
    async uploadRecording(recordingPath) {
      const uploadManager = getUploadManager()

      try {
        const url = await uploadManager.upload(
          {
            path: recordingPath,
            name: `recording_${Date.now()}.mp3`,
            size: await this.getFileSize(recordingPath)
          },
          {
            onProgress: (percent) => {
              this.uploadProgress = percent
            }
          }
        )

        console.log('录音上传成功:', url)
        return url
      } catch (error) {
        console.error('录音上传失败:', error)
        throw error
      }
    }
  }
}

场景 2: 图片上传

async uploadImage(imagePath) {
  const uploadManager = getUploadManager()

  // 获取图片信息
  const imageInfo = await uni.getImageInfo({ src: imagePath })

  const url = await uploadManager.upload(
    {
      path: imagePath,
      name: `image_${Date.now()}.jpg`,
      size: imageInfo.size || 0
    },
    {
      onProgress: (percent) => {
        uni.showLoading({ title: `上传中 ${percent}%` })
      },
      onSuccess: () => {
        uni.hideLoading()
        uni.showToast({ title: '上传成功', icon: 'success' })
      },
      onFailure: (error) => {
        uni.hideLoading()
        uni.showToast({ title: `上传失败: ${error.message}`, icon: 'none' })
      }
    }
  )

  return url
}

场景 3: 大文件上传(自动分片)

async uploadLargeFile(filePath) {
  const uploadManager = getUploadManager()

  // 大文件(> 10MB)会自动使用分片上传
  const url = await uploadManager.upload(
    {
      path: filePath,
      name: 'large_file.mp4',
      size: 50 * 1024 * 1024 // 50MB
    },
    {
      onProgress: (percent) => {
        console.log(`分片上传进度: ${percent}%`)
      }
    }
  )

  return url
}

场景 4: 批量上传

async uploadMultipleFiles(files) {
  const uploadManager = getUploadManager()
  const results = []

  for (const file of files) {
    try {
      const url = await uploadManager.upload(file, {
        onProgress: (percent) => {
          console.log(`${file.name}: ${percent}%`)
        }
      })

      results.push({ success: true, file: file.name, url })
    } catch (error) {
      results.push({ success: false, file: file.name, error: error.message })
    }
  }

  return results
}

策略选择建议

场景 推荐策略 原因
Android 平台 Native 性能最优,内存占用最小
跨平台应用 UniApp 兼容性好,性能优秀
需要 OSS SDK 特定功能 WebView 可以使用完整的 OSS SDK
兜底方案 WebView 总是可用

故障排查

问题 1: 上传失败,提示"无可用的上传策略"

原因: 所有策略都未就绪或不支持

解决方案:

  1. 检查 WebView 是否已初始化(收到 webview_ready 信号)
  2. 检查是否为 Android 平台(Native 策略)
  3. 检查网络连接
  4. 查看日志输出

问题 2: WebView 策略一直未就绪

原因: WebView 未加载完成或通信失败

解决方案:

  1. 确认 WebView 组件已正确渲染
  2. 检查 hybrid/html/index.html 是否存在
  3. 查看 WebView 控制台日志
  4. 确认已监听 webview_ready 信号

问题 3: 大文件上传失败

原因: 网络超时或内存不足

解决方案:

  1. 检查网络连接稳定性
  2. 调整分片大小(减小 basePartSize)
  3. 增加重试次数
  4. 使用 Native 策略(内存占用更小)

更多资源