我正在尝试编写一个响应,以便在客户端保存到文件,而不是在浏览器窗口中打开。这就是我正在做的事情
$content = 'Some content.';
$response = \Response::make($content, 200);
$response->header('Content-Description', 'File Transfer');
$response->header('Content-Type', 'application/octet-stream');
$response->header('Content-Disposition', 'attachment; filename=somecontent.any);
$response->header('Content-Transfer-Encoding', 'binary');
$response->header('Expires', '0');
$response->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
$response->header('Pragma', 'public');
$response->header('Content-Length', strlen($content));
return $response;
不幸的是,它没有开始下载为文件。当我查看Firefox中的响应标头时,我得到了这个:
X-Powered-By: PHP/5.5.3
Server: Apache
Pragma: public
Keep-Alive: timeout=5, max=100
Expires: 0
Date: Mon, 27 Jan 2014 11:34:23 GMT
Content-Type: application/octet-stream
content-transfer-encoding: binary
Content-Length: 13
Content-Disposition: attachment; filename=somecontent.any
Content-Description: File Transfer
Connection: Keep-Alive
Cache-Control: must-revalidate, post-check=0, pre-check=0, private
Unknown Content Type
Unable to display responses of type "application/octet-stream"
我想知道我在这里做错了什么。
由于扩展名不同,我无法将其硬编码到服务器的配置中。但客户希望将内容作为文件下载而不是直接在浏览器窗口中打开。
现在我知道问题与原始查询作为ajax帖子发送的事实有关。如果我将其作为对常规链接的响应点击,那么它工作正常(立即开始下载)。但是如果查询是从JavaScript发布的,那么它就不会开始下载,而是尝试在浏览器的窗口中打开它,无论我给头文件。有没有办法让它以这种方式工作?
答案 0 :(得分:0)
您可以使用Response::download($pathToFile)
方法。有关更多选项,请参阅docs。
答案 1 :(得分:0)
我使用它并且效果很好!
// $config contains generated XML file as string.
$config = $this->generateConfig('apple', Input::all());
// Make response -> attach $config to response
$response = Response::make($config);
// Set headers
$response->headers->set('Content-Type', 'application/x-apple-aspen-config');
$response->headers->set('Content-Disposition', "attachment; filename='mail.mobileconfig'");
return $response;