Uniapp实现多种文件类型上传

一、前言

在移动端开发中,文件上传是常见的功能需求。本文将通过Uniapp框架,详细讲解如何实现支持多类型文件(图片、视频、文档等)的上传功能,并解决跨平台兼容性问题😄😄😄。


二、技术方案

2.1 核心API

Uniapp提供了以下关键API:

  • uni.chooseFile:文件选择
  • uni.uploadFile:文件上传
  • uni.getFileInfo:获取文件信息

2.2 平台差异处理

平台 文件选择方式 限制说明
H5 <input type="file"> 依赖浏览器实现
微信小程序 wx.chooseMessageFile 需配置合法域名
App plus.io 文件系统 需处理本地文件路径

三、完整实现代码

3.1 文件选择器封装

javascript 复制代码
// 多类型文件选择
function chooseFiles(fileType = 'all') {
  return new Promise((resolve, reject) => {
    const extnameMap = {
      image: ['png', 'jpg', 'jpeg'],
      video: ['mp4', 'mov'],
      document: ['pdf', 'doc', 'docx', 'xls']
    };

    uni.chooseFile({
      count: 5, // 最大选择数量
      extension: fileType === 'all' ? [] : extnameMap[fileType],
      success: res => {
        const files = res.tempFiles.map(item => ({
          path: item.path,
          name: item.name,
          size: item.size,
          type: item.type
        }));
        resolve(files);
      },
      fail: err => reject(err)
    });
  });
}

3.2 文件上传核心方法

javascript 复制代码
// 上传文件到服务器
async function uploadFile(file) {
  try {
    const formData = {
      userId: '123',
      fileType: file.type
    };

    const res = await uni.uploadFile({
      url: 'https://api.example.com/upload',
      filePath: file.path,
      name: 'file',
      formData,
      header: {
        'Authorization': 'Bearer token'
      }
    });

    return JSON.parse(res[1].data);
  } catch (error) {
    console.error('上传失败:', error);
    throw error;
  }
}

3.3 进度显示实现

javascript 复制代码
// 带进度上传
function uploadWithProgress(file, onProgress) {
  return new Promise((resolve, reject) => {
    const task = uni.uploadFile({
      url: 'https://api.example.com/upload',
      filePath: file.path,
      name: 'file',
      success: (res) => resolve(JSON.parse(res.data)),
      fail: reject,
      complete: () => task.offProgressUpdate()
    });

    task.onProgressUpdate((res) => {
      onProgress && onProgress({
        progress: res.progress,
        totalBytesSent: res.totalBytesSent,
        totalBytesExpectedToSend: res.totalBytesExpectedToSend
      });
    });
  });
}

四、界面实现示例

html 复制代码
<template>
  <view class="upload-container">
    <button @click="chooseFiles">选择文件</button>
    <view class="preview-list">
      <view v-for="(file, index) in files" :key="index" class="file-item">
        <image v-if="file.type.startsWith('image/')" :src="file.path" mode="aspectFit"/>
        <video v-else-if="file.type.startsWith('video/')" :src="file.path"/>
        <view v-else class="document-icon">
          <text>{{ getFileExt(file.name) }}</text>
        </view>
        <progress :percent="file.progress" show-info />
      </view>
    </view>
  </view>
</template>

<style>
/* 文件预览样式 */
.preview-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-top: 20px;
}

.file-item {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px dashed #ddd;
}

.document-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: #f0f0f0;
}
</style>

五、服务端配合建议

5.1 文件接收配置(Node.js示例)

javascript 复制代码
const multer = require('multer');
const storage = multer.diskStorage({
  destination: 'uploads/',
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    cb(null, `${Date.now()}${ext}`);
  }
});

const upload = multer({
  storage,
  limits: {
    fileSize: 1024 * 1024 * 50 // 50MB
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'video/mp4', 'application/pdf'];
    cb(null, allowedTypes.includes(file.mimetype));
  }
});

router.post('/upload', upload.single('file'), (req, res) => {
  // 处理上传成功逻辑
});

六、注意事项🐛

  1. 文件大小限制:需同时在前端和服务端设置
  2. 格式验证:不能仅依赖前端验证
  3. 安全处理
    • 重命名存储文件
    • 扫描恶意文件
    • 设置访问权限
  4. 性能优化
    • 图片压缩(可使用uni.compressImage)
    • 分片上传大文件
    • 断点续传
相关推荐
百思可瑞教育1 天前
Vue 生命周期详解:从初始化到销毁的全过程剖析
前端·javascript·vue.js·前端框架·uni-app·北京百思可瑞教育·百思可瑞教育
jingling5551 天前
uniapp | 快速上手ThorUI组件
前端·笔记·前端框架·uni-app
百思可瑞教育1 天前
uni-app 根据用户不同身份显示不同的tabBar
vue.js·uni-app·北京百思可瑞教育·北京百思教育
Q_Q19632884752 天前
python+springboot+uniapp微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统
spring boot·python·django·uni-app·node.js·php
百思可瑞教育2 天前
使用UniApp实现一个AI对话页面
javascript·vue.js·人工智能·uni-app·xcode·北京百思可瑞教育·百思可瑞教育
不想吃饭e2 天前
在uniapp/vue项目中全局挂载component
前端·vue.js·uni-app
00后程序员张2 天前
iOS App 混淆与资源保护:iOS配置文件加密、ipa文件安全、代码与多媒体资源防护全流程指南
android·安全·ios·小程序·uni-app·cocoa·iphone
不知名的前端专家2 天前
uniapp原生插件 TCP Socket 使用文档
网络·tcp/ip·uni-app·netty
fakaifa2 天前
【独立版】智创云享知识付费小程序 v5.0.23+小程序 搭建教程
小程序·uni-app·知识付费·源码下载·智创云享独立版
2501_916007472 天前
Transporter App 使用全流程详解:iOS 应用 ipa 上传工具、 uni-app 应用发布指南
android·ios·小程序·https·uni-app·iphone·webview