您好,我正在尝试使用StaticFileHandler在龙卷风和它的大部分工作,除了它输出的文件(.csv)在网页上,当我点击下载。保存文件的唯一方法是右键单击并说“将目标另存为”(但这并不适用于所有浏览器)。
如何强制下载文件?我知道我需要这样设置StaticFileHandler的头:
self.set_header('Content-Type','text-csv')
self.set_header('Content-Disposition','attachment')但我不知道如何设置它,因为它是一个默认的处理程序。
耽误您时间,实在对不起!
发布于 2014-02-05 09:48:07
扩展web.StaticFileHandler
class StaticFileHandler(web.StaticFileHandler):
def get(self, path, include_body=True):
if [some csv check]:
# your code from above, or anything else custom you want to do
self.set_header('Content-Type','text-csv')
self.set_header('Content-Disposition','attachment')
super(StaticFileHandler, self).get(path, include_body)不要忘记在处理程序中使用扩展类!
发布于 2021-03-18 02:42:33
由于注释可能会被删除,因此正确的解决方案(如Jan的注释中所述)是:
web.StaticFileHandler的文档明确建议不要重写get方法。类方法'set_extra_headers(path)‘是受支持的,并且可以改为使用。
正确的解决方案应该如下所示:
class StaticFileHandler(web.StaticFileHandler):
@classmethod
def set_extra_headers(self, path):
if path.endswith('.csv'):
self.set_header('Content-Type', 'text-csv')
self.set_header('Content-Disposition', 'attachment')https://stackoverflow.com/questions/17725025
复制相似问题