我正在尝试向用户发送一个zip文件。
$file_info = get_file_info($filepath_name);
header("Content-Type: " . get_mime_by_extension($filepath_name));
header("Content-Length: " . $file_info["size"]);
header_remove('Pragma');
header_remove('Cache-Control');
//header("Content-Type: application/force-download");
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.urlencode($filepath_name));
header('Location: file://'.$filepath_name);
readfile($filepath_name);
$filepath_name
设置为"D:\dev2.local\storage_users\1\export_data\course_2357.zip"。
CCD_ 2返回正确大小的文件,但是该文件仍然没有被提供用于下载。
我已经尝试了所有的标题设置组合,但都没有用。
header('Location: file://'.$filepath_name);
看起来有问题。这是header
函数的特殊用途,它向浏览器发送302重定向HTTP状态,重定向到指定的URL。
这里没有添加任何内容,我会删除它。
ZIP存档的正确MIME类型是application/zip
,而不是application/octet-stream
。发送正确的标头使浏览器更有可能在正确的程序中打开文件。
对文件的完整路径进行URL编码会产生69个字符长的文件名。我认为这不太可能长到足以引起问题,但我们不妨通过发送基本名称"course_2357.zip"来简化它。我认为对文件名进行URL编码根本没有必要-这似乎源于Internet Explorer 8的黑客攻击,目的是让UTF-8字符发挥作用,而这在您的情况下是不需要的-但我保留了它,因为它不会造成任何伤害。
我使用了PHP内置的filesize
而不是get_file_info
,因为我没有安装CodeIgniter。我想这就是这个函数的来源吧?
以下代码基于您在上面提供的内容对我有效:
header("Content-Length: " . filesize($filepath_name));
header_remove('Pragma');
header_remove('Cache-Control');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename='.urlencode(basename($filepath_name)));
readfile($filepath_name);
我不知道这是否是你输入的顺序,但是:你试过放入吗:
$filepath_name = "D:\dev2.local\storage_users\1\export_data\course_2357.zip"
在代码顶部,或者至少在readfile()
之前
正在等待您的更新。
您的标头似乎有问题。
你可以试试这样的东西:
ob_start();
//OR
ob_clean();
header("Content-Type: " . get_mime_by_extension($filepath_name));
/* Other code */
发现问题:
这个功能是通过AJAX调用调用的,这就是php不允许发送文件的原因。
找到的解决方案:必须将文件路径和名称返回到php所在的js,并从js中提供文件。
编辑:这是我使用的变通方法:
var hostname = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
jQuery('<iframe>', {
src: hostname + value.return_zip,
id: 'iFrame_zip_download',
frameborder: 0,
scrolling: 'no'
}).appendTo('#export_import_status');
其中value.return_zip是服务器上文件的相对路径(/storage_users/xx/xx/xx.zip)。然后我添加主机名,结果很好,例如:https://www.google.com/storage_users/xx/xx/xx.zip.iFrame隐藏在状态div中。