前端文件上传处理:别再让用户等待了!

前端文件上传处理:别再让用户等待了!

毒舌时刻

文件上传?听起来就像是前端工程师为了显得自己很专业而特意搞的一套复杂流程。你以为随便加个input[type=file]就能实现文件上传?别做梦了!到时候你会发现,大文件上传会导致页面崩溃,用户体验极差。

你以为FormData就能解决所有问题?别天真了!FormData在处理大文件时会导致内存溢出,而且无法显示上传进度。还有那些所谓的文件上传库,看起来高大上,用起来却各种问题。

为什么你需要这个

  1. 用户体验:良好的文件上传处理可以提高用户体验,减少用户等待时间。
  2. 性能优化:合理的文件上传策略可以减少服务器负担,提高上传速度。
  3. 错误处理:完善的错误处理可以避免上传失败时的用户困惑。
  4. 安全保障:安全的文件上传处理可以防止恶意文件上传,保障系统安全。
  5. 功能丰富:支持多文件上传、拖拽上传、进度显示等功能,满足不同场景的需求。

反面教材

// 1. 简单文件上传 <input type="file"> <button onclick="uploadFile()">Upload</button> function uploadFile() { const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; const formData = new FormData(); formData.append('file', file); fetch('/api/upload', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); } // 2. 忽略文件大小限制 function uploadFile() { const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; if (file.size > 10 * 1024 * 1024) { // 10MB alert('File too large'); return; } // 上传逻辑 } // 3. 忽略文件类型限制 function uploadFile() { const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']; if (!allowedTypes.includes(file.type)) { alert('Invalid file type'); return; } // 上传逻辑 } // 4. 缺少进度显示 function uploadFile() { const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; const formData = new FormData(); formData.append('file', file); fetch('/api/upload', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); } // 5. 忽略错误处理 function uploadFile() { const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; const formData = new FormData(); formData.append('file', file); fetch('/api/upload', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => console.log(data)); } 

问题

  • 简单文件上传,无法处理大文件
  • 忽略文件大小限制,导致服务器负担过重
  • 忽略文件类型限制,可能上传恶意文件
  • 缺少进度显示,用户体验差
  • 忽略错误处理,上传失败时用户不知道原因

正确的做法

基本文件上传

// 1. 单文件上传 function uploadFile() { const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; // 验证文件大小 if (file.size > 10 * 1024 * 1024) { // 10MB alert('File too large'); return; } // 验证文件类型 const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']; if (!allowedTypes.includes(file.type)) { alert('Invalid file type'); return; } const formData = new FormData(); formData.append('file', file); fetch('/api/upload', { method: 'POST', body: formData }) .then(response => { if (!response.ok) { throw new Error('Upload failed'); } return response.json(); }) .then(data => { console.log('Upload successful:', data); alert('File uploaded successfully'); }) .catch(error => { console.error('Upload error:', error); alert('Upload failed: ' + error.message); }); } // 2. 多文件上传 function uploadFiles() { const fileInput = document.getElementById('fileInput'); const files = fileInput.files; if (files.length === 0) { alert('Please select files'); return; } // 验证文件大小和类型 for (const file of files) { if (file.size > 10 * 1024 * 1024) { // 10MB alert(`File ${file.name} is too large`); return; } const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']; if (!allowedTypes.includes(file.type)) { alert(`File ${file.name} has invalid type`); return; } } const formData = new FormData(); for (const file of files) { formData.append('files', file); } fetch('/api/upload-multiple', { method: 'POST', body: formData }) .then(response => { if (!response.ok) { throw new Error('Upload failed'); } return response.json(); }) .then(data => { console.log('Upload successful:', data); alert('Files uploaded successfully'); }) .catch(error => { console.error('Upload error:', error); alert('Upload failed: ' + error.message); }); } 

带进度显示的文件上传

function uploadFileWithProgress() { const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; const progressBar = document.getElementById('progressBar'); if (!file) { alert('Please select a file'); return; } const formData = new FormData(); formData.append('file', file); fetch('/api/upload', { method: 'POST', body: formData, // 添加进度监听 onUploadProgress: function(progressEvent) { const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); progressBar.style.width = percentCompleted + '%'; progressBar.textContent = percentCompleted + '%'; } }) .then(response => { if (!response.ok) { throw new Error('Upload failed'); } return response.json(); }) .then(data => { console.log('Upload successful:', data); alert('File uploaded successfully'); }) .catch(error => { console.error('Upload error:', error); alert('Upload failed: ' + error.message); }); } // 使用XMLHttpRequest实现进度显示 function uploadFileWithProgressXHR() { const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; const progressBar = document.getElementById('progressBar'); if (!file) { alert('Please select a file'); return; } const formData = new FormData(); formData.append('file', file); const xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function(event) { if (event.lengthComputable) { const percentCompleted = Math.round((event.loaded * 100) / event.total); progressBar.style.width = percentCompleted + '%'; progressBar.textContent = percentCompleted + '%'; } }); xhr.addEventListener('load', function() { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText); console.log('Upload successful:', data); alert('File uploaded successfully'); } else { console.error('Upload error:', xhr.statusText); alert('Upload failed: ' + xhr.statusText); } }); xhr.addEventListener('error', function() { console.error('Upload error'); alert('Upload failed'); }); xhr.open('POST', '/api/upload'); xhr.send(formData); } 

拖拽上传

function setupDragAndDrop() { const dropArea = document.getElementById('dropArea'); // 拖拽事件 dropArea.addEventListener('dragover', function(event) { event.preventDefault(); dropArea.classList.add('drag-over'); }); dropArea.addEventListener('dragleave', function() { dropArea.classList.remove('drag-over'); }); dropArea.addEventListener('drop', function(event) { event.preventDefault(); dropArea.classList.remove('drag-over'); const files = event.dataTransfer.files; if (files.length > 0) { uploadFiles(files); } }); // 点击上传 dropArea.addEventListener('click', function() { document.getElementById('fileInput').click(); }); // 文件选择 document.getElementById('fileInput').addEventListener('change', function() { const files = this.files; if (files.length > 0) { uploadFiles(files); } }); } function uploadFiles(files) { // 验证文件 for (const file of files) { if (file.size > 10 * 1024 * 1024) { // 10MB alert(`File ${file.name} is too large`); return; } const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']; if (!allowedTypes.includes(file.type)) { alert(`File ${file.name} has invalid type`); return; } } // 上传逻辑 const formData = new FormData(); for (const file of files) { formData.append('files', file); } // 上传代码... } 

大文件分块上传

async function uploadLargeFile(file) { const chunkSize = 1024 * 1024; // 1MB const totalChunks = Math.ceil(file.size / chunkSize); const fileId = generateFileId(); for (let i = 0; i < totalChunks; i++) { const start = i * chunkSize; const end = Math.min(start + chunkSize, file.size); const chunk = file.slice(start, end); const formData = new FormData(); formData.append('file', chunk); formData.append('fileId', fileId); formData.append('chunkIndex', i); formData.append('totalChunks', totalChunks); formData.append('fileName', file.name); try { const response = await fetch('/api/upload-chunk', { method: 'POST', body: formData }); if (!response.ok) { throw new Error('Upload failed'); } const data = await response.json(); console.log(`Chunk ${i + 1}/${totalChunks} uploaded:`, data); } catch (error) { console.error('Upload error:', error); throw error; } } // 通知服务器合并 chunks const response = await fetch('/api/merge-chunks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ fileId, fileName: file.name, totalChunks }) }); if (!response.ok) { throw new Error('Merge failed'); } const data = await response.json(); console.log('File uploaded successfully:', data); return data; } function generateFileId() { return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); } 

最佳实践

// 1. 使用FileReader预览图片 function previewImage(file) { const reader = new FileReader(); reader.onload = function(e) { const img = document.createElement('img'); img.src = e.target.result; img.style.maxWidth = '200px'; document.getElementById('preview').appendChild(img); }; reader.readAsDataURL(file); } // 2. 压缩图片 function compressImage(file, maxWidth = 800, maxHeight = 800, quality = 0.8) { return new Promise((resolve) => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.onload = function() { let width = img.width; let height = img.height; if (width > height) { if (width > maxWidth) { height = (height * maxWidth) / width; width = maxWidth; } } else { if (height > maxHeight) { width = (width * maxHeight) / height; height = maxHeight; } } canvas.width = width; canvas.height = height; ctx.drawImage(img, 0, 0, width, height); canvas.toBlob(function(blob) { resolve(blob); }, file.type, quality); }; img.src = URL.createObjectURL(file); }); } // 3. 安全验证 function validateFile(file) { // 验证文件大小 if (file.size > 10 * 1024 * 1024) { // 10MB return { valid: false, message: 'File too large' }; } // 验证文件类型 const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']; if (!allowedTypes.includes(file.type)) { return { valid: false, message: 'Invalid file type' }; } // 验证文件扩展名 const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.pdf', '.doc', '.docx']; const extension = file.name.substring(file.name.lastIndexOf('.')); if (!allowedExtensions.includes(extension.toLowerCase())) { return { valid: false, message: 'Invalid file extension' }; } return { valid: true, message: 'File is valid' }; } // 4. 上传状态管理 class UploadManager { constructor() { this.uploads = new Map(); } async upload(file) { const id = generateFileId(); const upload = { id, file, status: 'pending', progress: 0, error: null }; this.uploads.set(id, upload); try { upload.status = 'uploading'; // 上传逻辑 // ... upload.status = 'completed'; upload.progress = 100; } catch (error) { upload.status = 'failed'; upload.error = error.message; } return upload; } getUpload(id) { return this.uploads.get(id); } getAllUploads() { return Array.from(this.uploads.values()); } cancelUpload(id) { const upload = this.uploads.get(id); if (upload) { upload.status = 'cancelled'; // 取消上传逻辑 // ... } } } // 使用 const uploadManager = new UploadManager(); const file = document.getElementById('fileInput').files[0]; uploadManager.upload(file).then(upload => { console.log('Upload result:', upload); }); 

毒舌点评

文件上传确实很重要,但我见过太多开发者滥用这个特性,导致应用变得过于复杂。

想象一下,当你为了实现大文件上传,使用了分块上传技术,结果导致代码变得非常复杂,这真的值得吗?

还有那些过度使用文件上传库的开发者,为了使用某个库,而忽略了项目的实际需求,结果导致代码变得过于复杂。

所以,在实现文件上传时,一定要根据实际需求来决定。不要为了实现所有功能而实现,要选择最适合的方案。

当然,对于需要上传大文件的应用来说,分块上传是必要的。但对于普通的文件上传需求,使用简单的FormData可能更加合适。

最后,记住一句话:文件上传的目的是为了方便用户上传文件,而不是为了炫技。如果你的文件上传实现导致用户体验变得更差,那你就失败了。

Read more

HarmonyOS 6实战:视频封面智能生成与AI集成

HarmonyOS 6实战:视频封面智能生成与AI集成

在移动应用开发中,视频内容处理是一个常见但充满挑战的领域。许多开发者在实现视频封面自动生成功能时,常常面临以下困境: * 处理速度慢:长视频帧提取耗时长,用户体验差 * 封面质量参差不齐:传统算法难以识别最具代表性的关键帧 * 资源消耗过大:内存占用高,在低端设备上表现不佳 * 算法复杂度高:需要兼顾多维度评价指标 * 适配性差:不同分辨率、编码格式的视频处理方式各异 * 个性化需求难满足:无法根据视频内容特性智能推荐最佳封面 本文将深入分析这些常见问题,并提供基于HarmonyOS的完整解决方案。 一、常见问题深度分析 1.1 性能与效率的平衡难题 问题表现: * 处理2分钟以上视频时,提取时间超过5秒 * 内存占用峰值超过200MB,容易触发OOM * 在低端设备上帧率不稳定,界面卡顿明显 * 电池消耗快,发热严重 根本原因: * 传统全量帧提取策略缺乏智能化 * 解码器配置不当,硬件加速未充分利用 * 内存管理策略不合理,频繁GC导致卡顿 * 并行处理能力不足,CPU资源利用率低 1.2 关键帧识别准确率低 问题表现: * 选

PyTorch生成式人工智能(18)——循环神经网络详解与实现

PyTorch生成式人工智能(18)——循环神经网络详解与实现

PyTorch生成式人工智能(18)——循环神经网络详解与实现 * 0. 前言 * 1. 文本生成的挑战 * 2. 循环神经网络 * 2.1 文本数据 * 2.2 循环神经网络原理 * 3. 长短期记忆网络 * 3. 自然语言处理基础 * 3.1 分词 * 3.2 词嵌入 * 3.3 词嵌入在自然语言处理中的应用 * 小结 * 系列链接 0. 前言 我们已经学习了如何生成数字和图像等内容。从本节开始,我们将主要聚焦于文本生成。人类语言极其复杂且充满细微差别,不仅仅涉及语法和词汇的理解,还包括上下文、语气和文化背景等。成功生成连贯且语境适当的文本是一项重大挑战,需要深入理解和处理语言。 1. 文本生成的挑战 人类主要通过语言进行交流,能够生成语言文本的人工智能可以更自然地与用户互动,使技术变得更加易于使用。文本生成有广泛的应用,包括自动化客户服务回复、创作文章和电影剧本创作、帮助创意写作,

一文读懂OpenRouter:全球AI模型的“超级接口”,很多免费模型

一文读懂OpenRouter:全球AI模型的“超级接口”,很多免费模型

在人工智能技术百花齐放的今天,开发者面临着一个“幸福的烦恼”:市面上有GPT-4、Claude、Gemini、Kimi、GLM等众多顶尖大模型,但每个平台都需要单独注册、管理API密钥、对接不同接口文档,极大地增加了开发成本与技术门槛。 OpenRouter的出现,正是为了解决这一痛点。它不仅是一个AI模型聚合平台,更被业界视为全球AI模型竞争的“风向标”。 1. 什么是OpenRouter? OpenRouter是一个开源的AI模型聚合平台,它像一个“超级接口”或“路由器”,将全球超过300个主流AI模型(来自400多个提供商)整合在一起,为开发者提供统一的API接口。 其核心价值在于: * 统一API接口:开发者只需使用一套API密钥,即可调用包括OpenAI、Anthropic、Google、以及中国头部厂商(如MiniMax、月之暗面、智谱AI)在内的所有模型,无需为每个模型单独适配接口。 * 智能路由与成本优化:平台支持智能路由,可自动匹配性价比最高的模型,或根据开发者需求手动切换。其采用纯按量付费模式,无月费或最低消费,价格通常与官方持平甚至更低。 * 零

重磅官宣!Token 官方中文名定了——「词元」,AI 术语终于有了统一标准

今天(3月24日)科技圈迎来一个里程碑式的消息:国家数据局在国新办新闻发布会上正式官宣,AI 领域核心术语 Token 的中文标准译名,确定为「词元」✅ 从此,困扰业内多年的 Token 译名乱象,终于有了官方定论。 作为每天和大模型、AI 交互的从业者/爱好者,相信大家都有过这样的困扰:同样是 Token,在区块链里叫「代币」,在网络安全领域叫「令牌」,在大模型场景里,有人叫「标记」,有人干脆不翻译直接用英文,甚至还有「模元」「智元」等多种民间译法,跨场景沟通时经常出现理解偏差。 而这次官方定调「词元」,绝非简单的翻译统一,背后藏着对 AI 核心逻辑的精准解读,也预示着我国 AI 产业的规范化再进一步。 一、官方定名核心要点,必看! * 发布主体:国家数据局局长刘烈宏在国新办发布会、中国发展高层论坛上正式使用「