我正在尝试使用symfony2创建一个下载文件的链接。
它确实下载了一个文件,但它不适用于我的Chrome。我不知道如何让它发挥作用。有人知道该怎么做吗?
JQuery代码:
$.ajax({
url: url,
type: "POST",
data: {id : id},
dataType: "json",
success: function(resp){
console.log(resp);
},
error: function(x, y, z){
//console.log( x );
}
});
控制器中的PHP代码:
$response = new Response();
// Set headers
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', mime_content_type($filename));
$response->headers->set('Content-Disposition', 'attachment; filename="' . basename($filename) . '"');
$response->headers->set('Content-length', filesize($filename));
// Send headers before outputting anything
$response->sendHeaders();
$response->setContent(file_get_contents($filename));
答案 0 :(得分:0)
有一个与所有浏览器兼容的解决方案:不要使用Ajax来执行此操作。相反,写一个简单的“location.href”指令,如下所示:
$("#download").on('click', function() {
location.href = "{{ path('download_file', { 'fileId': file.id }) }}";
});
你的Symfony控制器可能是(例如):
/**
* @Route("/download_file/{fileId}", name="download_file")
*/
public function downloadFileAction($fileId)
{
$filename = ....
$response = new Response();
$response->headers->set('Content-Type', mime_content_type($filename));
$response->headers->set('Content-Disposition', 'attachment; filename="' . basename($filename) . '"');
$response->headers->set('Content-Length', filesize($filename));
$response->headers->set('Pragma', "no-cache");
$response->headers->set('Expires', "0");
$response->headers->set('Content-Transfer-Encoding', "binary");
$response->sendHeaders();
$response->setContent(readfile('LOCATION_OF_FILE/'.$filename));
return $response;
}
您的文件将自动下载,您的用户将保留在当前页面上,这就是您的期望。