【问题标题】:How to return .xlsx file?如何返回 .xlsx 文件?
【发布时间】:2014-11-26 23:22:23
【问题描述】:

如何返回 .xlsx 文件?

例如 - 当我要去“/download”时 - “File.xlsx”应该开始下载。

我正在使用瓶子 0.12.7 和 python 3.4 我尝试退货:

@route('/download')
def download():
    return open('files/File.xlsx')

但 Chrome 会返回此错误:ERR_EMPTY_RESPONSE

谢谢。

【问题讨论】:

  • 实际发生了什么(你的代码我看不到)?
  • @doctorlove 问题已编辑。
  • 尝试实际读取文件内容:return open('files/File.xlsx').read()
  • @ch3ka 当我尝试设置 "encoding='utf-8' " 我有 "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb2 in position 15: invalid start byte"
  • 你要发送什么Content-type: 标头?

标签: python python-3.x bottle


【解决方案1】:

您需要明确设置内容类型标头。

Excel 文件的内容类型是 application/vnd.ms-excel 用于 .xls 文件或 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 用于 .xlsx 文件,所以试试这个:

response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

完整代码:

@route('/download')
def download():
    response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    return open('files/File.xlsx')

【讨论】:

  • Chrome 返回我:ERR_EMPTY_RESPONSE
  • 请尝试使用wgetcurl(甚至是Firefox),看看会得到什么响应。
猜你喜欢
  • 2019-06-09
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多