📘 前端文件服务技术文档

版本: 1.0.0
最后更新: 2024年
适用项目: 文件管理系统、云存储前端

📁 一、服务概述

本项目包含两个核心前端服务:

🛠️ 二、快速开始

1. 安装与引入

// 在Vue/React组件或普通JS文件中
import { fileService } from './services/file-service.js';
import uploadService from './services/presigned-upload-service.js';

2. 基础配置

确保环境变量已配置:

VITE_API_URL=http://your-api-server.com

📚 三、核心API参考

FileService 主要方法

方法参数返回示例
getFiles(params) { page, limit, parentId, sort, order } { files[], pagination, total } await fileService.getFiles({ page: 1, limit: 20 })
uploadFile(file, options) File对象,{ onProgress, prefix } { success, fileKey, url } await uploadService.uploadFile(file, { onProgress: (p) => console.log(p) })
batchDownload(fileIds) [fileId1, fileId2, ...] { success, fileCount, zipSize? } await fileService.batchDownload(['id1', 'id2'])
previewFile(fileId) 文件ID字符串 { success, url, fileType } await fileService.previewFile('file-123')

PresignedUploadService 主要方法

方法说明使用场景
getUploadUrl()获取临时上传URL自定义上传逻辑
uploadFileWithXHR()直接XHR上传需要精细控制的上传
uploadFiles()批量上传多文件上传界面
checkService()检查服务状态上传前健康检查

🎯 四、使用场景示例

场景1:完整的文件上传流程

// 1. 用户选择文件
const fileInput = document.getElementById('file-input');
const file = fileInput.files[0];

// 2. 使用PresignedUploadService上传到对象存储
const uploadResult = await uploadService.uploadFile(file, {
    onProgress: (progress) => {
        console.log(`上传进度: ${progress.percentage}%`);
    }
});

// 3. 上传成功后,文件已保存在对象存储中
// (后端会自动记录,或可手动调用其他API)

场景2:文件管理界面

// 加载文件列表
const { files } = await fileService.getFiles({ parentId: null });

// 渲染文件列表
files.forEach(file => {
    // 根据文件类型显示不同图标
    const canPreview = fileService.isPreviewSupported(file);
    // 显示下载、预览、删除等按钮
});

// 处理文件操作
async function handleFileAction(fileId, action) {
    switch(action) {
        case 'download':
            await fileService.downloadFile(fileId);
            break;
        case 'preview':
            const preview = await fileService.previewFile(fileId);
            openPreviewModal(preview.url);
            break;
        case 'delete':
            await fileService.deleteFile(fileId);
            break;
    }
}

⚠️ 五、注意事项

  1. 确保用户已登录(token存在于localStorage)
  2. 大文件上传建议使用分片上传(服务已支持)
  3. 批量下载时注意浏览器并发限制(建议使用后端打包)
  4. 预览功能依赖文件类型和后端支持情况
  5. 上传进度监控需要现代浏览器支持

🔧 六、调试与开发

在开发环境下,可通过控制台直接调用服务:

// 检查服务状态
await uploadService.checkService();

// 测试上传
await window.testUpload('测试内容');

// 查看当前下载状态
fileService.downloadManager.activeDownloads;
提示: 两个服务设计为互补使用。FileService处理业务逻辑,PresignedUploadService处理存储交互。在大多数情况下,直接使用FileService的高级方法即可,PresignedUploadService作为底层支持。