Flask 文件上传,删除上传的文件

 目录结构

Flask 文件上传,删除上传的文件

 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/', 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




    File Manager


    

File Manager

Upload a file:

Files:

    {% for file in files %}
  • {{ file }}
  • {% endfor %}

效果图

版权声明:如无特殊标注,文章均来自网络,本站编辑整理,转载时请以链接形式注明文章出处,请自行分辨。

本文链接:https://www.shbk5.com/dnsj/73353.html