[英]force file download handling
我試圖了解如何為強制下載創建響應以及瀏覽器如何處理它。
在本文之后: 教程。
我有一個腳本,它發送一個文件作為對下載的響應。
<?php
// it's a zip file
header('Content-Type: application/zip');
// 1 million bytes (about 1megabyte)
header('Content-Length: 1000000');
// load a download dialogue, and save it as download.zip
header('Content-Disposition: attachment; filename="download.zip"');
// 1000 times 1000 bytes of data
for ($i = 0; $i < 1000; $i++) {
echo str_repeat(".",1000);
// sleep to slow down the download
// sleep(5);
}
sleep(5);
當sleep()
function 在循環內時,它會在文件開始下載之前等待一段時間。
但是當放置在循環之外時,文件會立即開始下載。
誰能幫我理解這種行為?
第二種情況的問題是您在調用睡眠 function 之前將文件發送到客戶端。 您可以將 output 存儲在內部緩沖區中,並在睡眠 function 后發送。 (我不建議將此用於生產用途。)試試這個修改后的程序:
<?php
// it's a zip file
header('Content-Type: application/zip');
// 1 million bytes (about 1megabyte)
header('Content-Length: 1000000');
// load a download dialogue, and save it as download.zip
header('Content-Disposition: attachment; filename="download.zip"');
//Turn on output buffering
ob_start();
// 1000 times 1000 bytes of data
for ($i = 0; $i < 1000; $i++) {
echo str_repeat(".",1000);
// sleep to slow down the download
// sleep(5);
}
//Store the contents of the output buffer
$buffer = ob_get_contents();
// Clean the output buffer and turn off output buffering
ob_end_clean();
sleep(5);
echo $buffer;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.