目录结构
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>
效果图文章来源:https://www.toymoban.com/news/detail-608100.html
文章来源地址https://www.toymoban.com/news/detail-608100.html
到了这里,关于Flask 文件上传,删除上传的文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!