如何使用 Vanilla JavaScript 上传文件并添加加载动画
文件上传对于任何 Web 应用程序来说都是非常普遍的,当通过互联网(在浏览器上)上传文件和资源时,事情可能会有些压力。幸运的是,有了 HTML 5,通常带有表单控件以允许用户修改数据的输入元素在简化资源上传方面变得如此方便。
在本文中,我们将仔细研究如何使用普通 JavaScript 处理文件上传。目的是教您如何在不需要外部库的情况下构建文件上传组件,并学习 JavaScript 中的一些核心概念。您还将学习如何在上传时显示上传的进度状态。
源代码:像往常一样,您可以修改项目的 GitHub 存储库上托管的源代码。
项目设置
首先,在您的首选目录中,为项目创建一个新文件夹:
$ mkdir file-upload-progress-bar-javascript
完成此操作后,现在让我们创建 index.html、main.css 和 app.js 文件,我们将在其中编写项目的所有标记。
$ touch index.html && touch main.css && touch app.js
现在我们可以通过使用
创建一个基本的 HTML 模板来开始构建文件上传的结构。和<主体>标签:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>File Upload with Progress Bar using JavaScript</title> </head> <body></body> </html>
接下来,我们在 main.css 中添加项目的基本样式:
* { margin: 0; padding: 0; box-sizing: border-box; }
为了增强应用程序的外观,我们将使用 font Awesome 库中的图标,我们可以通过在官方 font Awesome 库网站上创建的套件代码将其添加到我们的项目中。
现在,index.html 已更新,并且 main.css 文件已链接:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="https://kit.fontawesome.com/355573397a.js" crossorigin="anonymous" ></script> <link rel="stylesheet" href="main.css"> <title>File Upload with Progress Bar using JavaScript</title> </head> <body></body> </html>
我们继续构建文件上传器的结构:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="https://kit.fontawesome.com/355573397a.js" crossorigin="anonymous" ></script> <link rel="stylesheet" href="main.css" /> <title>File Upload with Progress Bar using JavaScript</title> </head> <body> <div class="file-upload__wrapper"> <header>File Uploader JavaScript with Progress</header> <div class="form-parent"> <form action="#" class="file-upload__form"> <input class="file-input" type="file" name="file" hidden /> <i class="fas fa-cloud-upload-alt"></i> <p>Browse File to Upload</p> </form> <div> <section class="progress-container"></section> <section class="uploaded-container"></section> </div> </div> </div> <script src="app.js"></script> </body> </html>
然后,复制/粘贴以下代码来更新 main.css:
* { margin: 0; padding: 0; box-sizing: border-box; } body { min-height: 100vh; background: #cb67e9; display: flex; align-items: center; justify-content: center; font-family: Arial, Helvetica, sans-serif; } ::selection { color: white; background: #cb67e9; } .file-upload__wrapper { width: 640px; background: #fff; border-radius: 5px; padding: 35px; box-shadow: 6px 6px 12px rgba(0, 0, 0, 0.05); } .file-upload__wrapper header { color: #cb67e9; font-size: 2rem; text-align: center; margin-bottom: 20px; } .form-parent { display: flex; align-items: center; gap: 30px; justify-content: center; } .file-upload__wrapper form.file-upload__form { height: 150px; border: 2px dashed #cb67e9; cursor: pointer; margin: 30px 0; display: flex; align-items: center; flex-direction: column; justify-content: center; border-radius: 6px; padding: 10px; } form.file-upload__form :where(i, p) { color: #cb67e9; } form.file-upload__form i { font-size: 50px; } form.file-upload__form p { font-size: 1rem; margin-top: 15px; } section .row { background: #e9f0ff; margin-bottom: 10px; list-style: none; padding: 15px 12px; display: flex; align-items: center; justify-content: space-between; border-radius: 6px; } section .row i { font-size: 2rem; color: #cb67e9; } section .details span { font-size: 1rem; } .progress-container .row .content-wrapper { margin-left: 15px; width: 100%; } .progress-container .details { display: flex; justify-content: space-between; align-items: center; margin-bottom: 7px; } .progress-container .content .progress-bar-wrapper { height: 10px; width: 100%; margin-bottom: 5px; background: #fff; border-radius: 30px; } .content .progress-bar .progress-wrapper { height: 100%; background: #cb67e9; width: 0%; border-radius: 6px; } .uploaded-container { overflow-y: scroll; max-height: 230px; } .uploaded-container.onprogress { max-height: 160px; } .uploaded-container .row .content-wrapper { display: flex; align-items: center; } .uploaded-container .row .details-wrapper { display: flex; flex-direction: column; margin-left: 15px; } .uploaded-container .row .details-wrapper .name span { color: green; font-size: 10px; } .uploaded-container .row .details-wrapper .file-size { color: #404040; font-size: 11px; }
现在,该组件在浏览器上应该看起来更好:
添加上传功能
为了在我们的项目中添加上传所需的功能,我们现在使用 app.js 文件,我们在其中编写 JavaScript 代码,为我们的项目赋予生命力。
将以下内容复制/粘贴到 app.js 中:
const uploadForm = document.querySelector(".file-upload__form"); const myInput = document.querySelector(".file-input"); const progressContainer = document.querySelector(".progress-container"); const uploadedContainer = document.querySelector(".uploaded-container"); uploadForm.addEventListener("click", () => { myInput.click(); }); myInput.onchange = ({ target }) => { let file = target.files[0]; if (file) { let fileName = file.name; if (fileName.length >= 12) { let splitName = fileName.split("."); fileName = splitName[0].substring(0, 13) + "... ." + splitName[1]; } uploadFile(fileName); } }; function uploadFile(name) { let xhrRequest = new XMLHttpRequest(); const endpoint = "uploadFile.php"; xhrRequest.open("POST", endpoint); xhrRequest.upload.addEventListener("progress", ({ loaded, total }) => { let fileLoaded = Math.floor((loaded / total) * 100); let fileTotal = Math.floor(total / 1000); let fileSize; fileTotal < 1024 ? (fileSize = fileTotal + " KB") : (fileSize = (loaded / (1024 * 1024)).toFixed(2) + " MB"); let progressMarkup = `<li class="row"> <i class="fas fa-file-alt"></i> <div class="content-wrapper"> <div class="details-wrapper"> <span class="name">${name} | <span>Uploading</span></span> <span class="percent">${fileLoaded}%</span> </div> <div class="progress-bar-wrapper"> <div class="progress-wrapper" style="width: ${fileLoaded}%"></div> </div> </div> </li>`; uploadedContainer.classList.add("onprogress"); progressContainer.innerHTML = progressMarkup; if (loaded == total) { progressContainer.innerHTML = ""; let uploadedMarkup = `<li class="row"> <div class="content-wrapper upload"> <i class="fas fa-file-alt"></i> <div class="details-wrapper"> <span class="name">${name} | <span>Uploaded</span></span> <span class="file-size">${fileSize}</span> </div> </div> </li>`; uploadedContainer.classList.remove("onprogress"); uploadedContainer.insertAdjacentHTML("afterbegin", uploadedMarkup); } }); let data = new FormData(uploadForm); xhrRequest.send(data); }
我们所做的是能够读取使用文件输入元素选择的文件,并在 DOM 上创建新的文件列表。文件上传时会显示进度,文件上传完成后进度状态会变为已上传。
然后,我们还在项目中添加了一个 uploadFile.php 来模拟发送文件的端点。这样做的原因是为了在我们的项目中模拟异步,从而得到进度加载的效果。
<?php $file_name = $_FILES['file']['name']; $tmp_name = $_FILES['file']['tmp_name']; $file_up_name = time().$file_name; move_uploaded_file($tmp_name, "files/".$file_up_name); ?>
结论
您能读完本文的这一步真是太棒了。
在本教程中,您学习了如何构建文件上传组件并为其添加进度条。当您构建网站并希望用户有参与感并了解上传文件的速度有多慢或多快时,这可能很有用。您可以随时重复使用该项目。
如果你在学习本教程时遇到困难,我建议你将你的项目上传到 GitHub 上寻求其他开发者的帮助,或者你也可以向我发送一条私信,我很乐意为你提供帮助。
这是该项目的 GitHub 存储库的链接。
相关资源
- FontAwesome 文档
以上是如何使用 Vanilla JavaScript 上传文件并添加加载动画的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

在PHP中,应使用password_hash和password_verify函数实现安全的密码哈希处理,不应使用MD5或SHA1。1)password_hash生成包含盐值的哈希,增强安全性。2)password_verify验证密码,通过比较哈希值确保安全。3)MD5和SHA1易受攻击且缺乏盐值,不适合现代密码安全。

PHP和Python各有优势,选择依据项目需求。1.PHP适合web开发,尤其快速开发和维护网站。2.Python适用于数据科学、机器学习和人工智能,语法简洁,适合初学者。

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP在电子商务、内容管理系统和API开发中广泛应用。1)电子商务:用于购物车功能和支付处理。2)内容管理系统:用于动态内容生成和用户管理。3)API开发:用于RESTfulAPI开发和API安全性。通过性能优化和最佳实践,PHP应用的效率和可维护性得以提升。

PHP类型提示提升代码质量和可读性。1)标量类型提示:自PHP7.0起,允许在函数参数中指定基本数据类型,如int、float等。2)返回类型提示:确保函数返回值类型的一致性。3)联合类型提示:自PHP8.0起,允许在函数参数或返回值中指定多个类型。4)可空类型提示:允许包含null值,处理可能返回空值的函数。

PHP仍然具有活力,其在现代编程领域中依然占据重要地位。1)PHP的简单易学和强大社区支持使其在Web开发中广泛应用;2)其灵活性和稳定性使其在处理Web表单、数据库操作和文件处理等方面表现出色;3)PHP不断进化和优化,适用于初学者和经验丰富的开发者。

PHP和Python各有优劣,选择取决于项目需求和个人偏好。1.PHP适合快速开发和维护大型Web应用。2.Python在数据科学和机器学习领域占据主导地位。

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。
