我正在使用ajax调用download.php页面,但它不起作用。下面的代码中有什么问题。
AJAX::
$.ajax({
type: "POST",
url: 'downloadsample.php',
data: {
imagepath: "../ReportCard/imagepost.png"
},
success:function(data) {
alert('sample download done ');
}
});
PHP代码::
<?php
if ( isset($_POST["imagepath"]) && !empty($_POST["imagepath"]) ) {
$file = $_POST['imagepath'];
// Fetch the file info.
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
else {
die('The provided file path is not valid.');
}
}
?>
您不能通过ajax直接下载文件。您可以将用户重定向到您的下载页面,也可以尝试使用iframe。我的意思是使用隐藏的iframe或动态生成你喜欢的iframe,并将这个iframe的来源放在你的下载URL中。
您不能通过Ajax来实现,因为JavaScript不能将文件直接保存到用户的计算机上(出于安全考虑)。不幸的是,将主窗口的URL指向文件下载意味着你几乎无法控制文件下载时的用户体验。
试试jQuery File Download,它允许"类似Ajax"的文件下载体验,并配有OnSuccess和OnFailure回调,以提供更好的用户体验。看看关于插件解决的常见问题和一些使用方法的博客文章,以及jQuery文件下载的演示。这是的来源
下面是一个简单的用例演示,使用带有promise的插件源代码。演示页面还包括许多其他"更好的用户体验"示例。
$.fileDownload('some/file.pdf')
.done(function () { alert('File download a success!'); })
.fail(function () { alert('File download failed!'); });