Download a file by clicking a button

妖精的绣舞 提交于 2021-02-05 12:10:56

问题


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.


回答1:


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.)



来源:https://stackoverflow.com/questions/19278106/download-a-file-by-clicking-a-button

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!