php - 强制文件下载处理
问题描述
我试图了解如何为强制下载创建响应以及浏览器如何处理它。
在本文之后:教程。
我有一个脚本,它发送一个文件作为对下载的响应。
<?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()
函数在循环内时,它会在文件开始下载之前等待一段时间。
但是当放置在循环之外时,文件会立即开始下载。
谁能帮我理解这种行为?
解决方案
第二种情况的问题是您在调用 sleep 函数之前将文件发送到客户端。您可以将输出存储在内部缓冲区中,并在睡眠功能后发送。(我不建议将此用于生产用途。)试试这个修改后的程序:
<?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;
推荐阅读
- html - 如何使用 VBA 和选择器获取 HTML 中标签的第 n 项以导出到 Excel
- r - 使用cross()在不同尺度上重新编码多个变量
- python - Matplotlib 中的对角线或弯曲错误
- dynamics-crm - 检查 Dynamics 365 CRM 中用户的剩余 API 调用限制
- angular - 我在我的 Angular 项目中找不到 e2e 文件夹
- python - 类型错误:列表索引必须是整数或切片,而不是 st
- node.js - 在 prisma create 上自动添加 UUID 关系
- c - 当用户输入新数据时,如何确保我的数据不会被覆盖?[C 结构和文件]
- flutter - 在颤动中单击相机按钮后手电筒重新启动
- reactjs - 当 id 未知时,CRA + react-intl 崩溃