目录结构
app.py
from flask import Flask, request, render_template, redirect, url_for
import os
app = Flask(__name__)
BASE_DIR = os.getcwd()
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'testfile')
@app.route('/')
def home():
files = os.listdir(UPLOAD_FOLDER)
return render_template('index.html', files=files)
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
file.save(os.path.join(UPLOAD_FOLDER, file.filename))
return redirect(url_for('home'))
@app.route('/delete/<filename>', methods=['POST'])
def delete_file(filename):
os.remove(os.path.join(UPLOAD_FOLDER, filename))
return redirect(url_for('home'))
if __name__ == "__main__":
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app.run(debug=True)
templates / index.html
<!DOCTYPE html>
<html>
<head>
<title>File Manager</title>
</head>
<body>
<h1>File Manager</h1>
<h2>Upload a file:</h2>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
<h2>Files:</h2>
<ul>
{% for file in files %}
<li>
{{ file }}
<form action="/delete/{{ file }}" method="post">
<input type="submit" value="Delete">
</form>
</li>
{% endfor %}
</ul>
</body>
</html>
效果图