文件上传并显示真是进度条

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传</title>
    <style>
        .upload-container {
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
        }

        .progress-container {
            margin: 20px 0;
            display: none;
        }

        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background-color: #4CAF50;
            width: 0%;
            transition: width 0.3s ease;
        }

        .progress-text {
            text-align: center;
            margin-top: 5px;
            font-size: 14px;
            color: #666;
        }

        .upload-btn {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .upload-btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }

        .file-info {
            margin: 10px 0;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }
    </style>
</head>

<body>
    <div class="upload-container">
        <h2>文件上传</h2>

        <div>
            <input type="file" id="fileInput" />
            <button class="upload-btn" id="uploadBtn" onclick="uploadFile()">上传文件</button>
        </div>

        <div class="file-info" id="fileInfo" style="display: none;">
            <div>文件名: <span id="fileName"></span></div>
            <div>文件大小: <span id="fileSize"></span></div>
        </div>

        <div class="progress-container" id="progressContainer">
            <div class="progress-bar">
                <div class="progress-fill" id="progressFill"></div>
            </div>
            <div class="progress-text" id="progressText">0%</div>
        </div>

        <div id="result" style="margin-top: 20px;"></div>
    </div>

    <script>
        function generateRequestId() {
            return 'req_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 显示文件信息
        function showFileInfo(file) {
            document.getElementById('fileInfo').style.display = 'block';
            document.getElementById('fileName').textContent = file.name;
            document.getElementById('fileSize').textContent = formatFileSize(file.size);
        }

        // 更新进度条
        function updateProgress(percentage) {
            const progressFill = document.getElementById('progressFill');
            const progressText = document.getElementById('progressText');
            const progressContainer = document.getElementById('progressContainer');

            progressContainer.style.display = 'block';
            progressFill.style.width = percentage + '%';
            progressText.textContent = percentage.toFixed(1) + '%';
        }

        // 轮询获取上传进度
        function pollUploadProgress(requestId, interval = 1000) {
            const progressInterval = setInterval(async () => {
                try {
                    const response = await fetch(`http://10.4.89.79:3002/user-api/resource/getUpLoadProgress/${requestId}`);
                    if (response.ok) {
                        const data = await response.json();
                        if (data.data !== undefined) {
                            updateProgress(data.data);

                            if (data >= 100) {
                                clearInterval(progressInterval);
                                setTimeout(() => {
                                    document.getElementById('progressContainer').style.display = 'none';
                                }, 2000);
                            }
                        }
                    }
                } catch (error) {
                    console.error('获取上传进度失败:', error);
                    clearInterval(progressInterval);
                }
            }, interval);

            return progressInterval;
        }

        // 上传文件
        async function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const uploadBtn = document.getElementById('uploadBtn');
            const resultDiv = document.getElementById('result');

            const file = fileInput.files[0];
            if (!file) {
                alert('请选择文件');
                return;
            }

            // 显示文件信息
            showFileInfo(file);

            // 生成请求ID
            const requestId = generateRequestId();

            // 准备表单数据
            const formData = new FormData();
            formData.append('file', file);
            formData.append('operatorType', '10');
            formData.append('requestId', requestId);

            // 禁用上传按钮
            uploadBtn.disabled = true;
            uploadBtn.textContent = '上传中...';

            // 显示进度条
            updateProgress(0);

            try {
                // 开始轮询进度
                const progressInterval = pollUploadProgress(requestId);

                // 发送上传请求
                const response = await fetch('http://www.xxx.com/upload', {
                    method: 'POST',
                    body: formData
                });

                // 清除进度轮询
                clearInterval(progressInterval);

                if (response.ok) {
                    const result = await response.json();
                    resultDiv.innerHTML = `<div style="color: green;">上传成功: ${JSON.stringify(result)}</div>`;
                    updateProgress(100);
                } else {
                    throw new Error(`上传失败: ${response.status} ${response.statusText}`);
                }

            } catch (error) {
                console.error('上传错误:', error);
                resultDiv.innerHTML = `<div style="color: red;">上传失败: ${error.message}</div>`;
            } finally {
                // 恢复上传按钮
                uploadBtn.disabled = false;
                uploadBtn.textContent = '上传文件';
            }
        }

        // 文件选择变化时显示文件信息
        document.getElementById('fileInput').addEventListener('change', function (e) {
            const file = e.target.files[0];
            if (file) {
                showFileInfo(file);
            }
        });
    </script>
</body>

</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容