Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Download via Ajax and PHP

i want to create a downloadscript which allows Force Download of JPGs. This is my php script:

<?php
    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Description: File Transfer");
    header("Content-Type: image/jpg");
    header('Content-Disposition: attachment; filename="'.basename($GET['a']).'"');
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".filesize(($GET['a']));
    readfile(($GET['a']);
?>

This is a code segment of my js code:

function downloadFile(a){
    document.location = "download.php?a="+ a;
}

With this code sample nothing happens. If i append the result into a HTML-tag, it shows the content of the file.

Any ideas how to teach the browser to download this file?

EDIT: SCRIPT UPDATE

like image 630
Sylnois Avatar asked Feb 08 '13 14:02

Sylnois


People also ask

Can we download file using Ajax?

We cannot download the file through Ajax, must use XMLHttpRequest.

Can you use Ajax with PHP?

Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.


1 Answers

You can't download files with ajax. So, if you have something that should happen on ajax, you should return url in response and apply it like document.location = "url"to start download process.

One note here. As I remember, browser will block file download if it is initiated not by user click. So, this will work fine:

.click(function(){
   document.location = "download url"
})

But if it is started not by user click, it will be blocked. So, code like this:

.click(function(){
       $.ajax({...,
       success:function(download_url_from_server){
           document.location = download_url_from_server;
       }});           
    })

will be blocked by browser. So, if you want to pass some data with a post, you may submit a form into hidden iframe or to blank page using <form target="...":

 function checkToken(token){
    var $form = $("#downloadForm");
    if ($form.length == 0) {
        $form = $("<form>").attr({ "target": "_blank", "id": "downloadForm", "method": "POST", "action": "script.php" }).hide();
        $("body").append($form);
    }
    $form.find("input").remove();
    var args = { a: "checkToken", b: token }
    for (var field in args) {
        $form.append($("<input>").attr({"value":args[field], "name":field}));
    }
    $form.submit();
}

And in script.php you need to execute code from download.php immediately, if token is Ok, or do a redirect to download script:

header("Location: download.php?a=" . $filename)
like image 63
Viktor S. Avatar answered Oct 19 '22 18:10

Viktor S.