【问题标题】:Download image by Python CGI [duplicate]通过 Python CGI 下载图像 [重复]
【发布时间】:2014-02-19 19:55:30
【问题描述】:

我有一个 Python cgi,可以将 svg 转换为 png 文件,然后我想将转换后的输出下载到用户的磁盘。

#the conversion stuff
print "Content-Type: image/png"
print "Content-Disposition: attachment; filename='pythonchart.png'"
print
print open("http:\\localhost\myproj\pythonchart.png").read()

这会生成一个包含 ‰PNG 的 png 文件。

有什么帮助吗?

【问题讨论】:

  • 您的文件系统上是否真的有一个名为"http:\\localhost\myproj\pythonchart.png" 的文件?因为open() 不执行 HTTP,但您报告的错误消息与您应该得到的不匹配。
  • 我将文件路径更改为我的项目的位置:“C:\wamp\www\myproj\pythonchart.png”,我仍然得到同样的错误
  • 我也尝试过@teferi 的建议,但仍然是同样的问题:(
  • 您能否通过其他方式确认C:\wamp\www\myproj\pythonchart.png确实存在并且是一个有效的PNG文件?

标签: python image svg http-headers cgi


【解决方案1】:

你应该尝试以二进制模式打开open('filename', 'rb').read()

【讨论】:

  • 除非 OP 在 Windows 上,否则这绝对没有任何作用。
  • 从问题的 cmets 中,我们可以推断出 OP is 在 Windows 上。
【解决方案2】:

您正在从open() 返回的文本模式流中读取二进制数据,并将二进制数据写入文本模式标准输出流。您必须以二进制模式打开文件,并将标准输出转换为二进制模式。

import sys
print "Content-Type: image/png"
print "Content-Disposition: attachment; filename='pythonchart.png'"
print

if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
print open("C:\\wamp\\www\\myproj\\pythonchart.png", "rb").read()

参考:Python 2.x - Write binary output to stdout?

【讨论】:

  • 谢谢!如果我在 Linux RedHat 上怎么办?
  • 那么尝试打开C:\\wamp\\www\\myproj\\pythonchart.png肯定会失败。
  • 是的,我知道,我的意思是我的脚本会是什么样子? “rb”还能用吗?
  • 如果您使用的是 Linux,并且您更改了 open() 语句中的路径,那么我发布的脚本将为您正常工作。
猜你喜欢
  • 2014-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-29
  • 1970-01-01
  • 2013-03-05
相关资源
最近更新 更多