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

如何在Flask中提交表单并实现无重定向下载内容?

Flask表单提交后无跳转下载数据

我用Flask实现了一个表单,提交后会跳转到/download页面返回选择的参数数据,但希望不跳转页面直接触发下载,现有代码如下:

原始代码

app.py

from flask import Flask, render_template, request

app = Flask(__name__, template_folder='templates')

@app.route("/")
def home():
    return render_template('index.html')

@app.route("/download", methods=["GET"])
def download():
    return request.args

if __name__ == '__main__':
    app.run()

templates/index.html

<form method="get" action="download" id='download-form'>
  <select name="number">
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
  <input type="submit">
</form>

我尝试用Ajax阻止页面跳转,但不知道如何下载返回的字符串数据:

$('#download-form').on('submit', function(e) {
  e.preventDefault();
  $.ajax({
    type: 'GET',
    url: '/dwonload', // 注意这里有拼写错误,应为/download
    data: $('#download-form').serialize(),
    success: function(data) {
      console.log(data); // 如何下载这个数据?
    },
  });
});

解决方案

方案一:前端Ajax处理下载逻辑

修正Ajax的URL拼写错误,在success回调里通过创建Blob对象生成下载链接,模拟点击触发下载:

$('#download-form').on('submit', function(e) {
  e.preventDefault();
  $.ajax({
    type: 'GET',
    url: '/download',
    data: $('#download-form').serialize(),
    success: function(data) {
      // 将返回数据转为格式化的JSON字符串
      const jsonStr = JSON.stringify(data, null, 2);
      // 创建Blob对象
      const blob = new Blob([jsonStr], { type: 'application/json' });
      // 生成临时下载链接
      const url = URL.createObjectURL(blob);
      // 创建a标签触发下载
      const downloadLink = document.createElement('a');
      downloadLink.href = url;
      downloadLink.download = 'selected-data.json'; // 设置下载文件名
      document.body.appendChild(downloadLink);
      downloadLink.click();
      // 清理临时资源
      document.body.removeChild(downloadLink);
      URL.revokeObjectURL(url);
    },
    error: function() {
      alert('下载失败,请重试');
    }
  });
});

方案二:后端直接返回下载响应(无需Ajax)

修改Flask后端的/download路由,让它直接返回带有下载头的响应,前端通过隐藏iframe提交表单,避免页面跳转:

修改后的app.py

from flask import Flask, render_template, request, make_response
import json

app = Flask(__name__, template_folder='templates')

@app.route("/")
def home():
    return render_template('index.html')

@app.route("/download", methods=["GET"])
def download():
    # 获取表单参数并转为字典
    data = request.args.to_dict()
    # 生成格式化的JSON内容
    json_content = json.dumps(data, indent=2)
    # 创建响应并设置下载头
    response = make_response(json_content)
    response.headers["Content-Disposition"] = "attachment; filename=selected-data.json"
    response.headers["Content-Type"] = "application/json"
    return response

if __name__ == '__main__':
    app.run()

修改后的index.html

<form method="get" action="download" id='download-form' target="hidden-iframe">
  <select name="number">
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
  <input type="submit">
</form>
<!-- 隐藏iframe,用于接收表单提交响应,避免页面跳转 -->
<iframe name="hidden-iframe" style="display: none;"></iframe>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:25:21