前端页面
上传成功页面
python代码
from flask import Flask, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
import os
# 初始化Flask应用
app = Flask(__name__)
# 配置上传设置
app.config['UPLOAD_FOLDER'] = 'uploads' # 上传文件保存目录
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 最大上传文件大小:16MB
# 允许上传的文件扩展名
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
def allowed_file(filename):
"""检查文件扩展名是否被允许"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# 检查请求中是否有文件部分
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
# 如果用户没有选择文件,浏览器可能会提交一个空部分
if file.filename == '':
return redirect(request.url)
# 验证文件并保存
if file and allowed_file(file.filename):
# 使用secure_filename确保文件名安全
filename = secure_filename(file.filename)
# 保存文件到上传目录
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# 上传成功后显示成功页面
return render_template('success.html', filename=filename)
# GET请求时显示上传表单
return render_template('upload.html')
@app.route('/uploads/<filename>')
def uploaded_file(filename):
"""返回上传文件的路径(实际应用中可能需要更复杂的处理)"""
return f'文件已上传: {filename}'
if __name__ == '__main__':
app.run(debug=True)
前端代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>Flask 文件上传</title>
<!-- Bootstrap 4 CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"
crossorigin="anonymous">
<!-- Font Awesome 图标 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
body {
font-family: 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background-color: #f8f9fa;
padding: 40px 0;
}
.upload-container {
max-width: 600px;
margin: 0 auto;
background-color: white;
border-radius: 10px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
padding: 30px;
}
.upload-header {
text-align: center;
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 1px solid #eee;
}
.upload-header h1 {
color: #343a40;
font-weight: 600;
font-size: 1.8rem;
}
.upload-steps {
display: flex;
justify-content: space-between;
margin-bottom: 30px;
position: relative;
}
.upload-steps::before {
content: '';
position: absolute;
top: 15px;
left: 15%;
right: 15%;
height: 2px;
background-color: #e9ecef;
z-index: 1;
}
.step {
text-align: center;
position: relative;
z-index: 2;
width: 30%;
}
.step-icon {
width: 35px;
height: 35px;
border-radius: 50%;
background-color: #e9ecef;
color: #6c757d;
display: inline-flex;
align-items: center;
justify-content: center;
margin-bottom: 8px;
font-weight: bold;
}
.step.active .step-icon {
background-color: #28a745;
color: white;
}
.step-text {
font-size: 0.9rem;
color: #6c757d;
}
.step.active .step-text {
color: #28a745;
font-weight: 500;
}
.allowed-types {
font-size: 0.9rem;
color: #6c757d;
margin-top: 8px;
padding: 8px 12px;
background-color: #f8f9fa;
border-radius: 4px;
}
.file-input-area {
border: 2px dashed #ced4da;
border-radius: 8px;
padding: 40px 20px;
text-align: center;
margin-bottom: 25px;
transition: all 0.3s ease;
background-color: #fafafa;
}
.file-input-area:hover, .file-input-area.drag-over {
border-color: #28a745;
background-color: #f0fff4;
}
.file-input-area input[type="file"] {
display: none;
}
.select-file-btn {
background-color: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 6px;
margin-top: 15px;
cursor: pointer;
font-weight: 500;
transition: all 0.2s ease;
}
.select-file-btn:hover {
background-color: #0069d9;
transform: translateY(-2px);
}
.file-info {
margin-top: 20px;
padding: 15px;
border-radius: 6px;
background-color: #f8f9fa;
display: none;
}
.file-info.visible {
display: block;
border: 1px solid #d4edda;
background-color: #f0fff4;
}
.upload-actions {
text-align: center;
margin-top: 30px;
}
.upload-btn {
background-color: #28a745;
color: white;
border: none;
padding: 12px 30px;
border-radius: 6px;
font-size: 1.1rem;
font-weight: 500;
cursor: pointer;
transition: all 0.3s ease;
min-width: 200px;
}
.upload-btn:disabled {
background-color: #6c757d;
cursor: not-allowed;
transform: none;
}
.upload-btn:not(:disabled):hover {
background-color: #218838;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(40, 167, 69, 0.2);
}
.action-icon {
margin-right: 8px;
}
.instruction-text {
color: #495057;
margin-bottom: 5px;
}
.secondary-text {
color: #6c757d;
font-size: 0.9rem;
}
</style>
</head>
<body>
<div class="container">
<div class="upload-container">
<div class="upload-header">
<h1><i class="fas fa-cloud-upload-alt text-success mr-2"></i>文件上传</h1>
<p class="text-muted">按照步骤上传您的文件到服务器</p>
</div>
<!-- 步骤指示器 -->
<div class="upload-steps">
<div class="step active">
<div class="step-icon">1</div>
<div class="step-text">选择文件</div>
</div>
<div class="step">
<div class="step-icon">2</div>
<div class="step-text">确认文件</div>
</div>
<div class="step">
<div class="step-icon">3</div>
<div class="step-text">完成上传</div>
</div>
</div>
<div class="upload-form">
<form method="POST" enctype="multipart/form-data">
<!-- 文件选择区域 -->
<div class="file-input-area" id="fileDropArea">
<i class="fas fa-file-upload fa-3x text-muted mb-3"></i>
<p class="instruction-text">请选择或拖放文件到此处</p>
<p class="secondary-text">支持单次上传一个文件</p>
<label for="file" class="select-file-btn">
<i class="fas fa-folder-open action-icon"></i>选择文件
</label>
<input type="file" name="file" id="file">
</div>
<!-- 选中文件信息 -->
<div id="fileInfo" class="file-info">
<div class="d-flex justify-content-between align-items-center">
<div>
<i class="fas fa-file-check text-success mr-2"></i>
<span id="fileName">文件名</span>
</div>
<div>
<span id="fileSize" class="text-muted mr-3">文件大小</span>
<button type="button" id="removeFile" class="btn btn-sm btn-outline-danger">
<i class="fas fa-times"></i>
</button>
</div>
</div>
</div>
<!-- 文件格式说明 -->
<p class="allowed-types">
<i class="fas fa-info-circle text-primary mr-1"></i>
允许的文件类型: txt, pdf, png, jpg, jpeg, gif (最大 16MB)
</p>
<!-- 上传按钮区域 -->
<div class="upload-actions">
<button type="submit" class="upload-btn" id="uploadButton" disabled>
<i class="fas fa-paper-plane action-icon"></i>上传文件
</button>
</div>
</form>
</div>
</div>
</div>
<!-- Bootstrap JS 和依赖 -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct"
crossorigin="anonymous"></script>
<script>
// 获取DOM元素
const fileInput = document.getElementById('file');
const fileDropArea = document.getElementById('fileDropArea');
const fileInfo = document.getElementById('fileInfo');
const fileName = document.getElementById('fileName');
const fileSize = document.getElementById('fileSize');
const removeFileBtn = document.getElementById('removeFile');
const uploadButton = document.getElementById('uploadButton');
const steps = document.querySelectorAll('.step');
// 文件选择处理
fileInput.addEventListener('change', handleFileSelect);
// 移除文件
removeFileBtn.addEventListener('click', function() {
fileInput.value = '';
fileInfo.classList.remove('visible');
uploadButton.disabled = true;
updateSteps(0);
});
// 拖放功能
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
fileDropArea.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
fileDropArea.addEventListener('dragover', function() {
this.classList.add('drag-over');
});
fileDropArea.addEventListener('dragleave', function() {
this.classList.remove('drag-over');
});
fileDropArea.addEventListener('drop', function(e) {
this.classList.remove('drag-over');
const dt = e.dataTransfer;
const files = dt.files;
if (files.length > 0) {
fileInput.files = files;
handleFileSelect(e);
}
});
// 处理文件选择
function handleFileSelect(e) {
if (fileInput.files.length > 0) {
const file = fileInput.files[0];
fileName.textContent = file.name;
// 格式化文件大小
let sizeText;
if (file.size < 1024 * 1024) {
sizeText = (file.size / 1024).toFixed(2) + ' KB';
} else {
sizeText = (file.size / (1024 * 1024)).toFixed(2) + ' MB';
}
fileSize.textContent = sizeText;
// 显示文件信息,启用上传按钮
fileInfo.classList.add('visible');
uploadButton.disabled = false;
// 更新步骤指示器
updateSteps(1);
}
}
// 更新步骤指示器
function updateSteps(activeStepIndex) {
steps.forEach((step, index) => {
if (index === activeStepIndex) {
step.classList.add('active');
} else {
step.classList.remove('active');
}
});
}
</script>
</body>
</html>
成功弹窗代码
<!DOCTYPE html>
<html>
<head>
<title>上传成功</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 50px;
}
.success-message {
color: #4CAF50;
font-size: 1.2em;
}
a {
display: inline-block;
margin-top: 20px;
color: #2196F3;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>上传成功!</h1>
<p class="success-message">文件 "{{ filename }}" 已成功上传。</p>
<a href="{{ url_for('upload_file') }}">上传另一个文件</a>
</body>
</html>