Skip to main content
 首页 » 编程设计

python之如何让 flask 发送文件然后重定向

2025年02月15日12虾米姐

我想让我的 Flask 应用程序发送一个文件,然后重定向到主页。

def create_pdf(**kwargs): 
    page = PdfManager(**kwargs) 
    pdf_out = page.create_pdf() 
    response = make_response(pdf_out) 
    # redirect(url_for('home')) 
    response.headers['Content-Disposition'] = "attachment; filename=pdf-test.pdf" 
    response.mimetype = 'application/pdf' 
    return response 
 
app.route('/', methods=['GET', 'POST']) 
def home(): 
    create_pdf(foo='bar') 

这段代码在响应时正确地吐出了 pdf 文件,但我无法在下载 pdf 文件后使页面刷新或重定向。我不能使用 Flask 的 send_from_directory 方法,因为这个 pdf 文件是使用 StringIo 、 PdfFileWriter 对象动态生成的。

请您参考如下方法:

您可以使用 javascript 使“/”路径返回 html 响应:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <script> 
        setTimeout(function(){ 
            document.location = "/redirect-uri"; 
        }, 500) 
    </script> 
</head> 
<body> 
    <iframe width="0" height="0" src="/path-to-pdf.pdf"/> 
</body> 
</html>

如果 pdf 是动态生成的,您还应该像这样提供 pdf url

@route('/path-to-pdf.pdf') 
def pdf_generator(): 
    return create_pdf()