Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
882 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...