使用PHP/jQuery强制下载 [英] forcing a download using PHP / jQuery

查看:207
本文介绍了使用PHP/jQuery强制下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有关使用PHP强制下载的问题已经很多,但我找不到我做错了什么以及应该怎么做.

I know there are already many questions about forcing a download with PHP, but I can't find what I'm doing wrong and what should I do.

我有一个带有文件名的列表,我想通过单击一个按钮来下载其中一个文件名.

I'm having an list with filenames, and I want to download one of them by clicking a button.

我的jQuery:

$(".MappeDownload").on("click",function(e){
            e.stopPropagation();
            fileId=$(this).val()
            $.post("ajax/DownloadFile.php",{ id : fileId})
})

在服务器端,我有一个带有文件名和文件路径的表.

and on the server side I have a table with the file names and the file path.

$sql = "SELECT vUploadPfad, vUploadOriginname  FROM tabUpload WHERE zUploadId='$_POST[id]'";
$result =  mysql_query($sql) or die("");
$file = mysql_fetch_array($result);
$localfile = $file["vUploadPfad"];
$name=$file["vUploadOriginname"];
$fp = fopen($localfile, 'rb');
        header("Cache-Control: ");   
        header("Pragma: ");         
        header("Content-Type: application/octet-stream");
        header("Content-Length: " . filesize($localfile));
        header("Content-Disposition: attachment; filename='".$name."';");
        header("Content-Transfer-Encoding: binary\n");
        fpassthru($fp);
        exit;

AJAX请求成功,我获得了正确的标题(文件大小,文件名等...),但下载未开始.

The AJAX request is successful, I'm getting the right header(filesize, filename etc...) but the download are not starting.

推荐答案

您不需要ajax,只需重定向到强制下载的地址即可.页面不会更改,因此,您应该拥有location.href = "ajax/DownloadFile.php?id="+fileId而不是$.post("ajax/DownloadFile.php",{ id : fileId}),并且在您的PHP文件中将$ _POST转换为$ _GET

You don't need ajax, just redirect to the address that forces the download. The page will not change so, instead of $.post("ajax/DownloadFile.php",{ id : fileId}) you should have location.href = "ajax/DownloadFile.php?id="+fileId and, in your PHP file, convert your $_POST to $_GET

这篇关于使用PHP/jQuery强制下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆