• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
U盘失踪了
帮助2

 目录结构

学新通

 app.py

  1.  
    from flask import Flask, request, render_template, redirect, url_for
  2.  
    import os
  3.  
     
  4.  
    app = Flask(__name__)
  5.  
    BASE_DIR = os.getcwd()
  6.  
    UPLOAD_FOLDER = os.path.join(BASE_DIR, 'testfile')
  7.  
     
  8.  
    @app.route('/')
  9.  
    def home():
  10.  
    files = os.listdir(UPLOAD_FOLDER)
  11.  
    return render_template('index.html', files=files)
  12.  
     
  13.  
    @app.route('/upload', methods=['POST'])
  14.  
    def upload_file():
  15.  
    file = request.files['file']
  16.  
    file.save(os.path.join(UPLOAD_FOLDER, file.filename))
  17.  
    return redirect(url_for('home'))
  18.  
     
  19.  
    @app.route('/delete/<filename>', methods=['POST'])
  20.  
    def delete_file(filename):
  21.  
    os.remove(os.path.join(UPLOAD_FOLDER, filename))
  22.  
    return redirect(url_for('home'))
  23.  
     
  24.  
     
  25.  
     
  26.  
    if __name__ == "__main__":
  27.  
    if not os.path.exists(UPLOAD_FOLDER):
  28.  
    os.makedirs(UPLOAD_FOLDER)
  29.  
    app.run(debug=True)

templates / index.html

  1.  
    <!DOCTYPE html>
  2.  
    <html>
  3.  
    <head>
  4.  
    <title>File Manager</title>
  5.  
    </head>
  6.  
    <body>
  7.  
    <h1>File Manager</h1>
  8.  
     
  9.  
    <h2>Upload a file:</h2>
  10.  
    <form action="/upload" method="post" enctype="multipart/form-data">
  11.  
    <input type="file" name="file">
  12.  
    <input type="submit" value="Upload">
  13.  
    </form>
  14.  
     
  15.  
    <h2>Files:</h2>
  16.  
    <ul>
  17.  
    {% for file in files %}
  18.  
    <li>
  19.  
    {{ file }}
  20.  
    <form action="/delete/{{ file }}" method="post">
  21.  
    <input type="submit" value="Delete">
  22.  
    </form>
  23.  
     
  24.  
    </li>
  25.  
    {% endfor %}
  26.  
    </ul>
  27.  
    </body>
  28.  
    </html>

效果图

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgahbbf
系列文章
更多 icon
同类精品
更多 icon
继续加载