我想向用戶提供大型zip文件。當有兩個併發連接時,服務器耗盡內存(RAM)。我將內存量從300MB增加到4GB(Dreamhost VPS),然後工作正常。如何在不使用太多內存的情況下強制下載大文件?
我需要讓很多超過2個併發連接更多。實際的4GB將允許20個併發連接(太糟糕)。
好,我使用的是當前的代碼,需要的內存雙則實際文件的大小。這太糟糕了。我想要將文件「流式傳輸」給用戶。所以我會分配不超過被傳送給用戶的塊。
下面的代碼是我使用CI中的一個(PHP框架):
ini_set('memory_limit', '300M'); // it was the maximum amount of memory from my server
set_time_limit(0); // to avoid the connection being terminated by the server when serving bad connection downloads
force_download("download.zip", file_get_contents("../downloads/big_file_80M.zip"));exit;
的force_download功能如下(笨默認輔助函數):
function force_download($filename = '', $data = '')
{
if ($filename == '' OR $data == '')
{
return FALSE;
}
// Try to determine if the filename includes a file extension.
// We need it in order to set the MIME type
if (FALSE === strpos($filename, '.'))
{
return FALSE;
}
// Grab the file extension
$x = explode('.', $filename);
$extension = end($x);
// Load the mime types
@include(APPPATH.'config/mimes'.EXT);
// Set a default mime if we can't find it
if (! isset($mimes[$extension]))
{
$mime = 'application/octet-stream';
}
else
{
$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
}
// Generate the server headers
if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE)
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".strlen($data));
}
else
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
}
exit($data);
}
我試着我在Google中發現了一些基於塊的代碼,但文件總是被損壞。可能是因爲糟糕的代碼。
任何人都可以幫助我嗎?
您是否嘗試過重定向到用頭'Location'文件? – Dani 2011-06-01 02:27:07
像你剛剛關閉給用戶直接鏈接到文件... – NotMe 2011-06-01 02:35:20
我忘了告訴該文件夾中通過網絡不能訪問更好的聲音給我。這是出於安全原因。如果用戶通過身份驗證過程,我只是提供該文件。我會嘗試下面的建議,並會回來投票選出最佳答案。 – 2011-06-01 17:54:02