如何下载(流)symfony2中的大文件 [英] How to download (stream) large files in symfony2
问题描述
我想做什么:
用户点击了一个网址(例如:BASE-URL/download/json).
代码从数据库中获取大量数据,然后流将其传输到JSON文件中,并提示用户下载该文件.
What I want to do :
User hit a url (ex: BASE-URL/download/json).
Code fetch huge data from database and stream it into a JSON file and user is prompted to download that file.
我尝试过的事情:
创建了一个大(700 MB)JSON文件.
试图用代码打开它,但是引发了错误.
What I tried :
Created a large (700 MB) JSON file.
Tried opening it with code, but error was thrown.
file_get_contents($ file)
file_get_contents($file)
错误:
允许的内存大小已用完XXX个字节(尝试分配YYY 字节)
Allowed memory size of XXX bytes exhausted (tried to allocate YYY bytes)
我在Symfony2中工作.数据大小最大为700MB.无法增加分配的内存. 我怎样才能做到这一点?如果需要进一步的信息,请发表评论.
I am working in Symfony2. Data can be upto 700MB in size. Can't increase the allocated memory. How can I achieve this? Please comment if any further information is required.
推荐答案
在上述所有注释的帮助下,我能够实现自己想要的目标.
这是相同的代码.
I was able to achieve what I wanted with the help of all the above comments.
Here is the code for the same.
$response = new StreamedResponse();
$i = -999999;
$response->setCallback(function () {
while($i < 999999){
echo '{"G1ello":"hualala"}';
$i = $i + 1;
}
});
$filename = "Data.json";
$contentDisposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('Content-Disposition', $contentDisposition);
return $response;
它创建了一个大文件,我可以下载.正是我想要的.发布解决方案,以便它可以帮助遇到相同问题的人.
It created a large file which I was able to download. Exactly what I wanted. Posting the solution so that it can help someone with same issue.
这篇关于如何下载(流)symfony2中的大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!