Correct way to trigger a file download (in PHP)?

后端 未结 4 1601
长发绾君心
长发绾君心 2021-01-12 09:34

Quick (and hopefully easy) question: I need to trigger a download of a PDF file that\'s generated by a PHP file. I can do this:



        
相关标签:
4条回答
  • 2021-01-12 10:05

    EDIT

    Yes javascript, something like:

    <a href="download.php" onclick="this.innerHTML='Downloading..'; downloadPdf(this);">Download</a>
    

    If you need to actually understand when the download is started you probably need to call an iframe and then use the "onload" event on it.. for example:

    // javascript
    function downloadPdf(el) {
        var iframe = document.createElement("iframe");
        iframe.src = "download.php";
        iframe.onload = function() {
            // iframe has finished loading, download has started
            el.innerHTML = "Download";
        }
        iframe.style.display = "none";
        document.body.appendChild(iframe);
    }
    
    0 讨论(0)
  • 2021-01-12 10:06

    Automatically starting downloads usually use a meta tag inside a normal page:

    <META HTTP-EQUIV="REFRESH" CONTENT="10.0;URL=download.php">
    

    This example will redirect the browser in 10 seconds to download.php.

    0 讨论(0)
  • 2021-01-12 10:11

    The solution you have for download is fine. You may want to consider some visual feedback to the user, perhaps by using javascript to show a "Downloading, please wait message" on the current page when the link is clicked via an onclick handler. Or simply indicate that the download may take some time to start next to the link. Since IE will unload the page, stopping any GIF animations, I prefer text indications for file downloads.

    0 讨论(0)
  • 2021-01-12 10:13

    fake it by using an onclick event handler to show a spinning gif

    <a href="download.php" onclick="ShowDownloading();">Download</a>
    
    0 讨论(0)
提交回复
热议问题