支持上传进度的文件上传

2024-07-14 10:02:39 245
支持进度条的文件上传,前端使用axios实现,后端使用 Node.js处理上传请求。

前端实现 (axios)

HTML 文件 (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload with Progress</title>
    <style>
        #progressBar {
            width: 100%;
            background-color: #f3f3f3;
        }
        #progress {
            width: 0%;
            height: 30px;
            background-color: #4caf50;
        }
    </style>
</head>
<body>
    <input type="file" id="fileInput">
    <button onclick="uploadFile()">Upload</button>
    <div id="progressBar">
        <div id="progress"></div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="uploadWithAxios.js"></script>
</body>
</html>

JavaScript 文件 (uploadWithAxios.js):

function uploadFile() {
    const fileInput = document.getElementById('fileInput');
    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append('file', file);

    // 使用 axios 发送 POST 请求进行文件上传
    axios.post('http://localhost:3000/upload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        // 配置上传进度条
        onUploadProgress: function(progressEvent) {
            // 计算上传进度百分比
            let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            document.getElementById('progress').style.width = percentCompleted + '%';
        }
    }).then(response => {
        console.log('File uploaded successfully', response);
    }).catch(error => {
        console.error('Error uploading file', error);
    });
}

后端实现 (Node.js)

  1. 安装所需包:

    npm init -y
    npm install express multer
    
  2. 创建 index.js 文件:

    const express = require('express');
    const multer = require('multer');
    const path = require('path');
    
    const app = express();
    const port = 3000;
    
    // 配置 multer 存储设置
    const storage = multer.diskStorage({
        destination: function (req, file, cb) {
            // 指定文件存储路径
            cb(null, 'uploads/');
        },
        filename: function (req, file, cb) {
            // 设置文件名
            cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
        }
    });
    
    // 创建 multer 实例
    const upload = multer({ storage: storage });
    
    // 处理文件上传的 POST 请求
    app.post('/upload', upload.single('file'), (req, res) => {
        res.send('File uploaded successfully');
    });
    
    // 启动服务器
    app.listen(port, () => {
        console.log(`Server running at http://localhost:${port}/`);
    });
    
  3. 创建 uploads 文件夹用于存储上传的文件:

    mkdir uploads