在浏览器上从gridFS流式传输音频/视频文件 [英] stream audio/video files from gridFS on the browser

查看:404
本文介绍了在浏览器上从gridFS流式传输音频/视频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从mongoDB读取音频文件,该文件是使用GridFS存储的.我可以在系统中下载文件并从中播放文件,但我想从数据库本身流式传输这些音频/视频文件并在浏览器中播放.无论如何,无需将文件下载到系统中就可以做到这一点?任何帮助都会很好.

I have been trying to read an audio file from mongoDB which i have stored using GridFS. I could download the file in the system and play from it but I wanted to stream those audio/video files from the DB itself and play it in the browser. Is there anyway to do that without downloading the file to the system? Any help would be good.

推荐答案

PHP GridFS支持具有 MongoGridFSFile :: getResource()函数,该函数使您可以将流作为 resource 获取-不会将整个文件加载到内存中.与fread/echo stream_copy_to_stream 结合使用,您可以防止将整个文件加载到内存中.使用stream_copy_to_stream,您可以简单地将GridFSFile流的资源复制到STDOUT流:

The PHP GridFS support has a MongoGridFSFile::getResource() function that allows you to get the stream as a resource - which doesn't load the whole file in memory. Combined with fread/echo or stream_copy_to_stream you can prevent the whole file from being loaded in memory. With stream_copy_to_stream, you can simply copy the GridFSFile stream's resource to the STDOUT stream:

<?php
$m = new MongoClient;
$images = $m->my_db->getGridFS('images');

$image = $images->findOne('mongo.png');

header('Content-type: image/png;');
$stream = $image->getResource();

stream_copy_to_stream( $stream, STDOUT );
?>

或者,您可以在返回的$stream资源上使用fseek(),仅将流的一部分发送回客户端.结合 HTTP范围请求,您可以执行这很有效.

Alternatively, you can use fseek() on the returned $stream resource to only send back parts of the stream to the client. Combined with HTTP Range requests, you can do this pretty efficiently.

这篇关于在浏览器上从gridFS流式传输音频/视频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆