如何使flask发送文件然后重定向? [英] How to make flask to send a file and then redirect?
问题描述
我希望我的flask应用发送文件,然后重定向到主页.
I want my flask app to send a file and then redirect to the home page.
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
对象动态生成的.
This piece of code properly spits out the pdf file on response but I can't make the page to refresh or redirect after downloading the pdf file. I can't use send_from_directory
method of flask since this pdf file is dynamically generated using StringIo
, PdfFileWriter
objects.
推荐答案
您可以使"/"路径使用javascript返回HTML响应,例如:
You can make the "/" path return a html response with javascript like:
<!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网址,例如
If the pdf is dynamically generated, you should also serve the pdf url like
@route('/path-to-pdf.pdf')
def pdf_generator():
return create_pdf()
这篇关于如何使flask发送文件然后重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!