【问题标题】:How to force download to a client.. is printing on the browser如何强制下载到客户端..正在浏览器上打印
【发布时间】:2013-09-26 18:53:21
【问题描述】:

我正在尝试创建类似代理(在 PYTHON 中)的东西来下载,但我遇到了错误。我想强制用户下载文件,而是在屏幕上打印(二进制代码)。这是我的代码: 我正在做的是......从另一台服务器下载文件,同时尝试将此文件发送到客户端。 所以是这样的:REMOTE_SERVER -> MY_SERVER -> CLIENT,而不必将文件保存在我的服务器中。有没有人可以帮助我做错了什么?

myfile = session.get(r.headers['location'], stream = True)
print "Content-Type: application/zip\r\n"
print "Prama: no-cache\r\n"
print "Expires: 0\r\n"
print "Cache-Control: must-revalidate, post-check=0, pre-check=0\r\n"
print "Content-Type: application/octet-stream\r\n"
print "Content-Type: application/download\r\n"
print "Content-Disposition: attachment; filename=ternos.205.zip\r\n"
print "Content-Transfer-Encoding: binary\r\n"
print "Content-Length: 144303765\r\n"

#print "Accept-Ranges: bytes\r\n"
print ("\r\n\r\n")
#with open('suits.zip', 'wb') as f:
for chunk in myfile.iter_content(chunk_size=1024):
    if chunk:
        sys.stdout.write(chunk)
        sys.stdout.flush()

似乎标题无关紧要,因为我已经尝试了数百万种不同的标题..强制下载等...但什么也没发生..

【问题讨论】:

    标签: python sockets stream httprequest


    【解决方案1】:

    print已经在输出中包含换行符。请改用sys.stdout,并且只写一个 Content-Type 标头。在标题之后,只写一个更多\r\n组合。

    import sys
    
    # ...
    sys.stdout.write("Content-Type: application/zip\r\n")
    sys.stdout.write("Prama: no-cache\r\n")
    sys.stdout.write("Expires: 0\r\n")
    sys.stdout.write("Cache-Control: must-revalidate, post-check=0, pre-check=0\r\n")
    sys.stdout.write("Content-Type: application/octet-stream\r\n")
    sys.stdout.write("Content-Disposition: attachment; filename=ternos.205.zip\r\n")
    sys.stdout.write("Content-Transfer-Encoding: binary\r\n")
    sys.stdout.write("Content-Length: 144303765\r\n")
    sys.stdout.write("\r\n")
    

    大多数 CGI 实现实际上会为您将常规的 \n 转换为 \r\n,因此您可以只打印标题而不添加分隔符:

    print "Content-Type: application/zip"
    print "Prama: no-cache"
    print "Expires: 0"
    print "Cache-Control: must-revalidate, post-check=0, pre-check=0"
    print "Content-Type: application/octet-stream"
    print "Content-Disposition: attachment; filename=ternos.205.zip"
    print "Content-Transfer-Encoding: binary"
    print "Content-Length: 144303765"
    print
    

    对于然后流式传输代理请求,我将使用 .raw 文件对象并将其传递给 sys.stdout 和 shutil.copyfileobj:

    import shutil
    
    shutil.copyfileobj(myfile.raw, sys.stdout)
    

    我怀疑是否需要刷新,而不是如果 Python 在此时退出并在关闭时刷新 stdout。

    【讨论】:

    • 仍然遇到同样的问题...我尝试了数百万次...在开发过程中我正在尝试在本地主机上...您认为这可能是原因吗?
    • 不,我不认为这有什么不同。您是否尝试过使用更手动的工具来查看返回的标头? telnet localhost <portnumber>,然后GET /path/to/script HTTP/1.0 加上双换行符给你什么?
    • 我只是使用了篡改数据并且没有发送标题...正在返回一个正常的 html 标题..但同时我在标题中看不到任何错误
    • 等一下..我刚刚发现我在页面顶部留下了一个内容类型...我会再试一次,稍后再回来
    • 如果您的脚本未提供标头或以正确的方式提供标头,HTTP 服务器将添加它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2011-07-26
    • 2011-06-03
    • 2012-01-10
    相关资源
    最近更新 更多