前端代码
index.htnml
<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload with Progress Bar | CodingNepal</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<div class="wrapper">
<header>File Uploader JavaScript</header>
<form action="#" enctype="multipart/form-data">
<input class="file-input" type="file" name="file" hidden>
<i class="fas fa-cloud-upload-alt"></i>
<p>Browse File to Upload</p>
</form>
<section class="progress-area"></section>
<section class="uploaded-area"></section>
</div>
<!-- 使用JavaScript来控制modal显示隐藏 -->
<!-- <button id="openModalBtn">打开提示框</button> -->
<div class="wap">
<div class="modal-container" id="modalBox" style="display:none;">
<div class="modal-box">
<span class="close-btn" aria-hidden="true"
onclick="document.getElementById('modalBox').style.display='none'">×</span>
<p class="message"></p>
<button class="action-btn" onclick="document.getElementById('modalBox').style.display='none'">确认</button>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
style.css
/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body{
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: #6990F2;
}
::selection{
color: #fff;
background: #6990F2;
}
.wrapper{
width: 430px;
background: #fff;
border-radius: 5px;
padding: 30px;
box-shadow: 7px 7px 12px rgba(0,0,0,0.05);
}
.wrapper header{
color: #6990F2;
font-size: 27px;
font-weight: 600;
text-align: center;
}
.wrapper form{
height: 167px;
display: flex;
cursor: pointer;
margin: 30px 0;
align-items: center;
justify-content: center;
flex-direction: column;
border-radius: 5px;
border: 2px dashed #6990F2;
}
form :where(i, p){
color: #6990F2;
}
form i{
font-size: 50px;
}
form p{
margin-top: 15px;
font-size: 16px;
}
section .row{
margin-bottom: 10px;
background: #E9F0FF;
list-style: none;
padding: 15px 20px;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: space-between;
}
section .row i{
color: #6990F2;
font-size: 30px;
}
section .details span{
font-size: 14px;
}
.progress-area .row .content{
width: 100%;
margin-left: 15px;
}
.progress-area .details{
display: flex;
align-items: center;
margin-bottom: 7px;
justify-content: space-between;
}
.progress-area .content .progress-bar{
height: 6px;
width: 100%;
margin-bottom: 4px;
background: #fff;
border-radius: 30px;
}
.content .progress-bar .progress{
height: 100%;
width: 0%;
background: #6990F2;
border-radius: inherit;
}
.uploaded-area{
max-height: 232px;
overflow-y: scroll;
}
.uploaded-area.onprogress{
max-height: 150px;
}
.uploaded-area::-webkit-scrollbar{
width: 0px;
}
.uploaded-area .row .content{
display: flex;
align-items: center;
}
.uploaded-area .row .details{
display: flex;
margin-left: 15px;
flex-direction: column;
}
.uploaded-area .row .details .size{
color: #404040;
font-size: 11px;
}
.uploaded-area i.fa-check{
font-size: 16px;
}
.modal-container {
position: absolute;
top: 20%;
left: 36%;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
/* background-color: rgba(0, 0, 0, 0.5); */
align-items: center;
z-index: 999;
}
.modal-box {
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
padding: 10px;
text-align: center;
max-width: 430px;
width: 90%;
font-family: Arial, sans-serif;
}
.close-btn {
float: right;
cursor: pointer;
color: #aaa;
font-size: 24px;
line-height: 1;
margin-top: -13px;
margin-right: -7px;
}
.close-btn:hover {
color: #000;
}
.message {
margin-bottom: 0.5rem;
text-indent: 2rem;
}
.action-btn{
border: 0;
width: 100px;
border-radius: 6px;
background-color: blue;
font-size: 12px;
padding: 4px;
color: white;
cursor: pointer;
}
script.js
const form = document.querySelector("form");
fileInput = document.querySelector(".file-input");
progressArea = document.querySelector(".progress-area");
uploadedArea = document.querySelector(".uploaded-area");
// 假设你有一个按钮来触发显示提示框
// form click event
form.addEventListener("click", () => {
fileInput.click();
});
fileInput.onchange = ({
target
}) => {
let file = target.files[0]; //getting file [0] this means if user has selected multiple files then get first one only
// console.log(file); //上传的文件
if (file) {
let fileName = file.name; //getting file name
if (fileName.length >= 12) { //if file name length is greater than 12 then split it and add ...
let splitName = fileName.split('.');
fileName = splitName[0].substring(0, 13) + "... ." + splitName[1];
}
uploadFile(fileName); //调用 uploadFile 并将文件名作为参数传递
}
}
// file upload function
function uploadFile(name) {
let formData = new FormData(form); //FormData is an object to easily send form data
axios.post('http://127.0.0.1:3000/upload/file', formData, {
onUploadProgress: function (progressEvent) {
let loaded = progressEvent.loaded; // 已上传的数据量
let total = progressEvent.total; // 总数据量
// 计算上传进度百分比
let percentCompleted = Math.round((loaded / total) * 100);
// 获取文件大小,单位转换与原问题中的逻辑一致
let fileTotal = Math.floor(total / 1024);
let fileSize;
if (fileTotal < 1024) {
fileSize = fileTotal + " KB";
} else {
fileSize = (loaded / (1024 * 1024)).toFixed(2) + " MB";
}
// 更新 UI 显示上传进度
let progressHTML = `<li class="row">
<i class="fas fa-file-alt"></i>
<div class="content">
<div class="details">
<span class="name">${name} • Uploading</span>
<span class="percent">${percentCompleted}%</span>
</div>
<div class="progress-bar">
<div class="progress" style="width: ${percentCompleted}%"></div>
</div>
</div>
</li>`;; // 根据进度生成 HTML 片段
progressArea.innerHTML = progressHTML;
// 如果上传完成
if (loaded === total) {
// 清除进度条并显示上传成功的状态
progressArea.innerHTML = "";
let uploadedHTML = `<li class="row">
<div class="content upload">
<i class="fas fa-file-alt"></i>
<div class="details">
<span class="name">${name} • Uploaded</span>
<span class="size">${fileSize}</span>
</div>
</div>
<i class="fas fa-check"></i>
</li>`; // 生成已上传文件的 HTML 片段
uploadedArea.classList.remove("onprogress");
uploadedArea.insertAdjacentHTML("afterbegin", uploadedHTML);
}
},
}).then(response => {
// 处理上传成功后的响应
if (response.data.code == 200) {
document.getElementById('modalBox').style.display = 'block';
document.querySelector(".message").style.color = "green"
document.querySelector(".message").innerHTML = "文件上传成功!!"
} else {
// 处理上传错误
document.getElementById('modalBox').style.display = 'block';
document.querySelector(".message").innerHTML = "文件上传失败!!"
document.querySelector(".message").style.color = "red"
console.log(error);
}
console.log(response);
}).catch(error => {
});
}
前端运行界面
后端代码
目录结构
需要下载的包
npm i express multer cors
index.js
const express = require("express")
const app = express()
const fs = require("fs")
const multer = require("multer");
const path = require("path");
let objMulter = multer({ dest: "./upload" }); //实例化multer,传递的参数对象,dest表示上传文件的存储路径
app.use(objMulter.any()); //any表示任意类型的文件
app.use(express.static("./public"));
// app.use(express.static("./public"))
// app.use(objMulter.image())//仅允许上传图片类型
// 配置跨域
app.use(require("cors")())
// 配置post解析
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.post("/upload/file", (req, res) => {
// throw new Error("服务器错误");
let oldName = req.files[0].path;
let newName = req.files[0].path + path.parse(req.files[0].originalname).ext;
// console.log(newName);
fs.renameSync(oldName, newName);
res.send({
message:"文件上传成功",
code: 200,
err: 0,
url: "http://localhost:3000/" +
req.files[0].filename +
path.parse(req.files[0].originalname).ext
});
})
// 错误中间件必须放最后
app.use((err, req, res, next) => {
console.log("服务器错误");
console.log(err.message);
res.send({
msg: "Error" + err.message,
code: 500,
data: {},
})
// next()
})
app.listen("3000", () => { console.log("3000端口执行"); })
运行结果