如何强制下载到客户端。。眉毛上印着

2024-04-26 23:19:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个类似于代理(PYTHON)的东西来下载,但是我得到了一个错误。我想强制用户下载一个文件,但是却在屏幕上打印(二进制代码)。这是我的代码: 我要做的是。。。从其他服务器下载文件,同时尝试将此文件发送到客户端。 类似于这样:远程服务器->我的服务器->客户机,而不必将文件保存在我的服务器中。有人能帮我做错事吗?在

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()

似乎这和头球没什么关系,因为我已经试过几百万个不同的头球了。。强制下载等。。。但什么也没发生。。在


Tags: 文件代码服务器streamapplicationchecktypestdout
1条回答
网友
1楼 · 发布于 2024-04-26 23:19:50

print已经在输出中包含一个换行符。使用sys.stdout,只写一个头。在标题之后,只写一个多个\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,因此您可以在不添加分隔符的情况下打印标题:

^{pr2}$

为了流式传输代理请求,我将使用.raw文件对象,并通过^{}将其传递给sys.stdout

import shutil

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

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

相关问题 更多 >