Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
880 views
in Technique[技术] by (71.8m points)

forcing a download using PHP / jQuery

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.

My 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
");
        fpassthru($fp);
        exit;

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...