昨晚这个工作正常,但我肯定不小心改变了什么东西,因为现在它不能工作了。
从这些标题中应该可以清楚地看出我想要做什么:
Content-Disposition: attachment;filename=english_customizable.xml
Location: http://tortoisewrath.com/files/2.xml
然而,当发送此标头时,在重定向后
Content-Disposition
部分不起作用。为什么呢?昨晚这个工作正常,但我肯定不小心改变了什么东西,因为现在它不能工作了。
从这些标题中应该可以清楚地看出我想要做什么:
Content-Disposition: attachment;filename=english_customizable.xml
Location: http://tortoisewrath.com/files/2.xml
Content-Disposition
部分不起作用。为什么呢?您试图做的事情是不可取的,可以查看此问题:Header Location + Content Disposition
Content-Disposition + Location header
但是,您可以这样做,为了使其正常工作,您必须在发送整个响应之前缓冲整个响应。您可以使用输出缓冲来实现此目的。
否则,浏览器可能会在文件下载之前解释Location
头。无论哪种方式都很棘手,所以您不应该想要这样做。
请注意,使用Content-Disposition: attachment;
强制“另存为”将确保客户端不会转到任何地方,因此下面的方法本身应该在任何情况下都可以正常工作。
在PHP中流式传输文件
引用一个头脑清晰的人的话:
// To use header() with 'content-type', why don't you use mime_content_type() function rather than checking the type on the basis of extension?
// Example code:
<?php
$file="test.docx";
header("Pragma: public");
header('Content-disposition: attachment; filename='.$file);
header("Content-type: ".mime_content_type($file));
header('Content-Encoding: identity');
ob_clean();
flush();
readfile($file);
?>
// Use $file to map to whichever type of file.
// Note: the mime types should already be defined in apache settings
来源:http://www.php.net/manual/en/function.header.php#107581
请注意,原始答案使用了在HTTP中实际上不存在的Content-Transfer-Encoding
。下面该源代码的评论对此进行了解释:http://www.php.net/manual/en/function.header.php#107044
echo file_get_contents(/* 文件路径 */)
将文件流式传输到客户端。这意味着你不能使用 Location
头部了。 - sg3s