正确的方法来触发文件下载(在PHP中)? [英] Correct way to trigger a file download (in PHP)?

查看:178
本文介绍了正确的方法来触发文件下载(在PHP中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速(并且希望容易)问题:我需要触发下载由PHP文件生成的PDF文件。我可以这样做:

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:

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

但是我应该这样做吗?可能吗?以上工作,但窗口显示加载...,直到下载开始。我想向用户提供一些反馈意见。

but should I be doing this another way? Javascript maybe? The above works but the window shows "Loading..." until the download starts. I'd like to provide some feedback to the user that something is happening.

想法?

注意:我已经有从服务器发送文件的代码。它工作完美。这个问题只是关于如何从客户端调用该脚本。

Note: I already have the code that sends the file from the server. It works perfectly. This question is simply about how best to call that script from the client.

某些网站有自动启动的下载。他们如何做?

Some sites have downloads that automatically start. How do they do that?

直接URL的问题是,如果PHP脚本错误,它将取代现有页面的e内容,这不是我

The problem with a direct URL is that if the PHP script errors it'll replace th econtent of the existing page, which is not what I want.

推荐答案

编辑

是javascript,类似于:

Yes javascript, something like:

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

如果您需要实际了解下载何时开始,您可能需要调用iframe然后使用onload事件就可以了..例如:

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);
}

这篇关于正确的方法来触发文件下载(在PHP中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆