简体   繁体   中英

Download a file by clicking a button

This is the HTML:

<button name="download">Download</button>

I want users to download a file when they click this button. For that, I'm using the following Ajax request:

$parent.find('button[name=download]').click(function () {
    $.ajax({
        url: "download.php",
        sucess: function(data, status, jqXHR){
            $console.text('Download efetuado');
        },
        error:function(xhr, status, error){
            $console.text(xhr.responseText);
        }
    });
});

Where download.php is:

if (file_exists($myFile)){
        header ("Content-Type: application/json");
        header ("Content-Disposition: attachment; filename=$fileName");
        header("Content-Length: " . filesize("$myFile"));
        $fp = fopen("$myFile", "r");
        fpassthru($fp);
    } else {
        echo "no file exists";
    }; 

This isn't outputing anything and no file is downloaded. I know the PHP script is working and is being called.

Don't use AJAX to download a file. It's not that it can't make the request and receive the response, it's just that it doesn't really have any meaningful way to handle the response.

The browser itself, on the other hand, does.

So you can just direct the browser to the request:

$parent.find('button[name=download]').click(function () {
    window.location.href = 'download.php';
});

If download.php is sending a response of Content-Disposition: attachment; then the page isn't going to be unloaded or modified in any way. The browser is going to handle the response of this request entirely separately from the current page context, and after handling the response that page context will remain.

(Unless, of course, the browser is configured to do something with that response, such as always display it instead of prompting to save it. But there's nothing you can do about that in code.)

At this point, in fact, it makes even more sense to just remove the JavaScript entirely and make it a normal link, which would accomplish the same thing:

<a href="download.php">Download</a>

You can style it to look like a button, which it probably more accessible than an actual button running JavaScript code. (If the browser doesn't have JavaScript enabled then the button would be useless, but a link would work just fine.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM