我按照这里的内容下载一个与存储名称不同名称的文件。但我并不完全理解所有内容,因为当我尝试使用ajax时,它不起作用。我示意我使用Smarty。
这是我的html代码:
// In $attache.id their is the id of the data i want to dowload in the database
<a href='javascript:uploadAttachFile({- $attache.id -});'><img src='../tools/telecharger.gif' /></a>
这是我的jQuery代码:
function uploadAttachFile(idAttache)
{
$.ajax({
//This permit me to go to the php function
url: ajaxURL("attacheUpload"),
type: "POST",
data: {
idAttache: idAttache
},
success: function(data)
{
alert(data);
}
})
}
这是我的php代码:
//Permit to have the path and new title of the file
$attacheEntite = Model_AttacheDB::getNameAndPathAttachFile(request('idAttache'));
$file = 'path' . $attacheEntite['path'];
if (file_exists($file))
{
header('Content-disposition: application/force-download; filename="' .$attacheEntite['titre']. '"');
header("Content-Type: application/pdf");
header('Content-Transfer-Encoding: binary');
header("Content-Length: " . filesize($file));
header("Pragma: ");
header("Expires: 0");
// upload the file to the user and quit
ob_clean();
flush();
readfile($file);
exit;
}
我知道它会通过我的php代码,因为ajax重新测试通过成功,并在我阅读它时提醒一个不可理解的代码,这个代码肯定是pdf文件的代码。
您不能让客户端通过ajax请求下载文件。
您在这里所做的是用PHP在服务器端读取文件,并将其内容返回给调用方脚本(事实上,您可以在"data"变量中看到内容)
如果没有ajax,您可以这样调用脚本:
<a href='path/to/your/phpscript.php' target='_blank' ><img src='../tools/telecharger.gif' /></a>
它会将文件发送到浏览器
编辑:如果您将属性target="_blank"添加到锚点,它将在新选项卡中打开下载,而无需重新加载当前页面