用Python提供文件下载
大家好,我正在尝试把一个旧的php脚本转换成python,但进展不太顺利。
这个脚本的目的是提供一个文件,同时隐藏它的来源。下面是php中可以正常工作的代码:
<?php
$filepath = "foo.mp3";
$filesize = filesize($filepath);
header("Pragma: no-cache");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
// force download dialog
//header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Disposition: attachment;filename="'.$filepath.'"');
header("Content-Transfer-Encoding: binary");
#header('Content-Type: audio/mpeg3');
header('Content-Length: '.$filesize);
@readfile($filepath);
exit(0);
?>
但是当我在python中做同样的事情时,下载的文件大小却是零字节。以下是我尝试的代码:
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
import cgitb; cgitb.enable()
filepath = "foo.mp3"
filesize = os.path.getsize(filepath)
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-Type: application/download"
print 'Content-Disposition: attachment;filename="'+filepath+'"'
print "Content-Transfer-Encoding: binary"
print 'Content-Length: '+str(filesize)
print #required blank line
open(filepath,"rb").read()
有没有人能帮帮我呢?
3 个回答
-1
你可以看看 urllib,它可以帮助你设置和处理请求头。这里有一个简单的例子,可以让你了解怎么做。
1
我不知道这是不是唯一的问题,但在Python中,打印输出时每一行的结束符是"\n",而HTTP头部的结束符需要用"\r\n"。
5
好吧,也许是我理解错了,但... 你其实并没有把文件的内容写到标准输出(stdout)上。你只是把它读到了内存里,所以这些内容不会在TCP连接的另一端显示出来...
试试这个:
sys.stdout.write(open(filepath,"rb").read())
sys.stdout.flush()
根据文件的大小,分块读取文件可能会更好,像这样:
chunk_size = 4096
handle = open(filepath, "rb")
while True:
buffer = handle.read(chunk_size)
if buffer:
sys.stdout.write(buffer)
else:
break
还有一点需要注意:如果你把二进制数据写入标准输出,可能会因为编码问题导致Python出错。这取决于你使用的Python版本。