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

FastAPI如何返回CSV文件内容为纯文本而非触发下载?

解决FastAPI返回CSV内容不触发下载的问题

浏览器收到text/csv类型响应时,部分浏览器默认会触发下载行为。要让内容直接在响应体中展示而非下载,只需通过响应头明确告知浏览器以内联方式处理内容。

修改后的代码示例

import time
from datetime import datetime
from fastapi import FastAPI, StreamingResponse

app = FastAPI()

# 假设process_hosts是你的CSV生成逻辑函数
def process_hosts(start, end):
    # 此处为生成CSV文件的业务逻辑
    pass

@app.get('/hosts/last_hour')
def hosts_last_hour():
    epoch_start = time.mktime(datetime.now().timetuple()) - 3600
    epoch_end = time.mktime(datetime.now().timetuple())
    process_hosts(epoch_start, epoch_end)
    
    def iterate_csv(epoch_start):
        # 改用文本模式读取并指定编码,适配text/csv的文本类型响应
        with open(f'output/hosts_traffic_{int(epoch_start)}.csv', mode='r', encoding='utf-8') as csv_file:
            yield from csv_file

    response = StreamingResponse(
        iterate_csv(epoch_start),
        media_type="text/csv",
        # 通过header指定内容以内联方式展示,阻止浏览器触发下载
        headers={"Content-Disposition": "inline"}
    )
    return response

关键修改说明

  • 添加Content-Disposition: inline响应头:直接告诉浏览器将内容渲染在页面中,而非作为附件下载。
  • 调整文件读取模式:将rb(二进制模式)改为r(文本模式)并指定编码,匹配text/csv的媒体类型,避免潜在的编码乱码问题。

内容的提问来源于stack exchange,提问作者José Oliveira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:37:09