You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask中向客户端发送文件后如何删除文件?(Windows适配)

Windows 11下Flask应用开发问题

我在Windows 11系统中开发一个小型Flask应用,核心需求:

  • 接收用户输入的字符串,生成文本文件并存放在static/text_files子文件夹
  • 通过页面锚点供用户下载,禁止使用Flask的send_file直接下载,也不能跳转页面

现有代码

app.py

#Package Imports
from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
import random

#Create Flask Form
#Create the Flask form here.
class MyForm(FlaskForm):
    text_field = StringField('Write here.', validators=[DataRequired()])
    submit_field = SubmitField('Submit')

#This function makes a text file with the user's text.
def make_text_file(my_string):
    filename = 'static/text_files/{}.txt'.format(random.randint(1, 1000000))
    with open(filename, 'w') as file:
        file.write(my_string)
    return '/'.join(filename.split('/')[1:])

#Create the Flask app here.
app = Flask(__name__)
app.config['SECRET_KEY'] = 'ABCDEFG'

@app.route('/', methods=['GET', 'POST'])
def index():
    result = False
    form = MyForm()
    
    if request.method == 'POST':
        text = request.form['text_field']
        result = make_text_file(text)
        return render_template('index.html', form=form, result=result)
    
    return render_template('index.html', form=form, result=result)

index.html

<html>
    <body>
        <form method="POST" action="{{ url_for('index') }}">
            <div class='form-div'>
                {{ form.csrf_token }}
                <div>{{ form.text_field }}</div>
                <div>{{ form.submit_field }}</div>
            </div>
        </form>
        
        <div id='result-link'>
            {% if result == False %}
                <div></div>
            {% else %}
                <a href="{{ url_for('static', filename=result) }}" download>Here is your file.</a>
            {% endif %}
        </div>
    </body>
</html>

尝试过的无效方案

  • 使用Flask的@after_this_request装饰器:路由同时处理GET和POST请求,无法指定仅在POST后执行文件删除;且该方案据说仅在Linux生效,我需要在Windows环境测试删除机制。
  • 使用Flask-SocketIO:运行Flask开发服务器时提示WebSocket传输不可用,不知道如何搭建生产环境服务器进行测试。

待解决问题

  1. 如何在Windows环境下实现生成文件后的自动删除逻辑?
  2. 最终要支持视频文件,将文件读入内存的方案是否可行?

内容的提问来源于stack exchange,提问作者Howsikan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 21:45:17