列出并从FTP下载单击的文件 [英] List and download clicked file from FTP

查看:92
本文介绍了列出并从FTP下载单击的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有FTP,我需要在上载目录中列出FTP中的所有文件,单击任何列出的文件后,它将从FTP下载特定文件.

I have FTP and I need list all files in FTP in uploads directory and after click on any listed file it will download the specific file from FTP.

它在上载目录中列出了我的文件,但是当我尝试下载文件时,它会键入无文件"

It list my files in uploads directory but when I will try to download file so it types me "no file"

我的代码:

    // connect and login to FTP server
$ftp_server = "IP";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, "name", "password");

// list all files in upload directory and with "a" download file from FTP
$target_dir = "uploads/";
$files = ftp_nlist($ftp_conn, $target_dir);
foreach($files as $file) {
    echo "<a href='$file' download>$file</a>";
    echo "<br>";
}

推荐答案

您在生成的<a>标记中的链接指向不包含链接文件的Web服务器.

Your link in the generated <a> tag points back to the web server, which does not contain the linked file.

您需要做的是链接到PHP脚本,并为其指定要下载的文件的名称.然后,该脚本将从FTP服务器下载文件,并将下载的文件传递回用户(至Web浏览器).

What you need to do is to link to a PHP script, giving it a name of the file to download. The script will then download the file from an FTP server and pass the downloaded file back to the user (to the webbrowser).

echo "<a href=\"download.php?file=".urlencode($file)."\">".htmlspecialchars($file)."</a>";

download.php脚本的非常简单的版本:

A very trivial version of the download.php script:

<?

header('Content-Type: application/octet-stream');

echo file_get_contents('ftp://username:password@ftp.example.com/path/' . $_GET["file"]);


download.php脚本使用 FTP URL包装器.如果您的Web服务器上不允许这样做,则必须更努力地使用FTP功能.看 PHP:如何从FTP服务器将文件读取为变量?


The download.php script uses FTP URL wrappers. If that's not allowed on your web server, you have to go the harder way with FTP functions. See PHP: How do I read a file from FTP server into a variable?

尽管对于一个真正正确的解决方案,您应该提供一些与文件相关的HTTP标头,例如Content-LengthContent-TypeContent-Disposition.

Though for a really correct solution, you should provide some HTTP headers related to the file, like Content-Length, Content-Type and Content-Disposition.

上述琐碎的示例还将首先将整个文件从FTP服务器下载到Web服务器.只有这样,它才会开始将其流式传输给用户(Web浏览器).这既浪费时间,又浪费网络服务器上的内存.

Also the above trivial example will first download whole file from the FTP server to the webserver. And only then it will start streaming it to the user (webbrowser). What is a waste of time and also of a memory on the webserver.

有关更好的解决方案,请参见通过PHP脚本从FTP服务器将文件下载到具有Content-Length标头的浏览器,而无需将文件存储在网络服务器.

For a better solution, see Download file via PHP script from FTP server to browser with Content-Length header without storing the file on the web server.

您可能还想自动检测Content-Type,除非您的所有文件都属于同一类型.

You may also want to autodetect Content-Type, unless all your files are of the same type.

这篇关于列出并从FTP下载单击的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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