我正在尝试使用cherryypy流式传输视频文件。当我进入localhost:8080/stream?video=video。Avi 开始下载,但几秒钟后就"完成"了。下载,无论文件有多大。我是新手,不知道为什么会这样。另外,如果文件是Matroska (.mkv),为什么它甚至不能识别?
这是我的Stream类:class Stream(object):
@cherrypy.expose
def default(self, video=None):
BASE_PATH = ".."
video = os.path.join(BASE_PATH, video)
if video == None:
return "no file specified!"
if not os.path.exists(video):
return "file not found!"
f = open(video)
size = os.path.getsize(video)
mime = mimetypes.guess_type(video)[0]
print(mime)
cherrypy.response.headers["Content-Type"] = mime
cherrypy.response.headers["Content-Disposition"] = 'attachment; filename="%s"' % os.path.basename(video)
cherrypy.response.headers["Content-Length"] = size
BUF_SIZE = 1024 * 5
def stream():
data = f.read(BUF_SIZE)
while len(data) > 0:
yield data
data = f.read(BUF_SIZE)
return stream()
default._cp_config = {'response.stream': True}
我意识到我所需要做的就是将open(video)更改为open(video, 'rb'),以便它以二进制模式读取文件。之后,文件完全下载并工作。