当前位置:首页 » 文件传输 » c实现从ftp上下载文件
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

c实现从ftp上下载文件

发布时间: 2023-05-11 22:37:33

‘壹’ C++程序中如何实现ftp多线程下载

本人不才,下面这个是从网络上转来的.不知可有帮助.

这是codeproject的关于ftp的实现,你可以去down源代码
Introction

StuffFTP is a free for life FTP client. This FTP client will allow you to connect to FTP servers and upload and download files.
Motivation

Why did I create and continue to support StuffFTP? First it is a learning experience, and since I just got laid off from my company, I decided to use some of the tools they have provided, its legal as I technically bought them and they do not have other programmers following in my footstep nor do they plan on hiring any, to create something for the community. I also used another FTP program that was freeware for a while and then became pay to use software with little to no notice. That irked me and a friend suggested I create my own FTP client. So I am.
Progress

This is currently a work in progress and I would be the first to say there is a lot of work to do. Since I am laid off, I have lots of time on my hands. And this is an excellent chance for me to learn some of the concepts of C++ that I wanted to, but never had the chance while I was working. I was hoping to get a job in San Jose, CA, but decided to hold off and live on saving for a while.
Guarantee

I will support this program as best as I can. I have already setup a website and forum for it, here. I use the forum because I have trouble responding to email especially when I get a whole bunch of SPAM everyday. There is no adware or spyware in the program, and I guarantee that it will be free for the life of the program.

Some people have already asked why I don't open source the project. The main reason is I do not know if I can. StuffFTP uses some proprietary third party libraries. I do not know if I can post the source code or header files to those libraries. So everyone will have to wait until I can get rid of those libraries or hear back from the companies concerning my question about releasing header and associated help files.
Tools

* MS Windows XP Professional
* MS Visual Studio .NET C++/MFC
* Clickteam Install Maker
* Clickteam Patch Maker
* Betaone.net forum members
* CXListCtrl by Hans Dietrich

3rd Party Libraries

The application uses Catalyst Socket Tools Library Edition and Professional UI GUI library. So far the support has been fair with Prof-UI and outstanding with Catalyst. The Catalyst tool is for the actual FTP connection and, as the name suggests, Prof-UI is being used for the GUI.
Updates

You can find the latest updates here and you can also find my latest ramblings, blogs, and support here. This is where you can find out all the latest versions and information.
How to contribute

Money! Just kidding you can contribute by downloading, using, and giving feedback on the program. That way I can determine which path to take with the application and which features to prioritize or not. Graphics is also where I need lots of help. I am left brained and can not draw a good stick figure to save my life. If you can help with graphics or anything else, please let me know. Also talk to me, I am bored. I have no job at the moment so I can use the company.
Features

* Able to upload/download from server/computer
* Connect to FTP sites using login
* Connect using other ports besides 21
* Delete, rename, and CHMOD a file

History

* 12/10/2003 - Version 0.11a
* 12/07/2003 - Version 0.10a

‘贰’ C#通过FTP下载文件夹

第一部分是实现单个文件下载的方法

///<summary>
///单个文件下载方法
///</summary>
///<paramname="adss">保存文件的本地路径</param>
///<paramname="ftpadss">下载文件的FTP路径</param>
publicvoiddownload(stringadss,stringftpadss)
{
//FileMode常数确定如何打开或创建文件,指定操作系统应创建新文件。
//FileMode.Create如果文件已存在,它将被改写
FileStreamoutputStream=newFileStream(adss,FileMode.Create);
FtpWebRequestdownRequest=(FtpWebRequest)WebRequest.Create(newUri(ftpadss));
//设置要发送到FTP服务器的命令
downRequest.Method=WebRequestMethods.Ftp.DownloadFile;
FtpWebResponseresponse=(FtpWebResponse)downRequest.GetResponse();
StreamftpStream=response.GetResponseStream();
longcl=response.ContentLength;
intbufferSize=2048;
intreadCount;
byte[]buffer=newbyte[bufferSize];
readCount=ftpStream.Read(buffer,0,bufferSize);
while(readCount>0)
{
outputStream.Write(buffer,0,readCount);
readCount=ftpStream.Read(buffer,0,bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}

第二个部分也就是需要遍历出所指定的文件夹内所有内容

首先是一个单个遍历文件夹获取文件夹下所有文件信息的方法

///</summary>
///<paramname="ftpads">FTP地址路径</param>
///<paramname="name">我们所选择的文件或者文件夹名字</param>
///<paramname="type">要发送到FTP服务器的命令</param>
///<returns></returns>
publicstring[]ftp(stringftpads,stringname,stringtype)
{
WebResponsewebresp=null;
StreamReaderftpFileListReader=null;
FtpWebRequestftpRequest=null;
try
{
ftpRequest=(FtpWebRequest)WebRequest.Create(newUri(ftpads+name));
ftpRequest.Method=type;
webresp=ftpRequest.GetResponse();
ftpFileListReader=newStreamReader(webresp.GetResponseStream(),Encoding.Default);
}
catch(Exceptionex)
{
ex.ToString();

}
StringBuilderstr=newStringBuilder();
stringline=ftpFileListReader.ReadLine();
while(line!=null)
{
str.Append(line);
str.Append("/n");
line=ftpFileListReader.ReadLine();
}
string[]fen=str.ToString().Split('/n');
returnfen;
}

之后是一个我们实现递归文件夹的方法

///<summary>
///下载方法KO
///</summary>
///<paramname="ftpads">FTP路径</param>
///<paramname="name">需要下载文件路径</param>
///<paramname="Myads">保存的本地路径</param>
publicvoiddownftp(stringftpads,stringname,stringMyads)
{
stringdownloadDir=Myads+name;
stringftpdir=ftpads+name;
string[]fullname=ftp(ftpads,name,WebRequestMethods.Ftp.ListDirectoryDetails);
//判断是否为单个文件
if(fullname.Length<=2)
{
if(fullname[fullname.Length-1]=="")
{
download(downloadDir+"/"+name,ftpads+name+"/"+name);
}
}
else
{
string[]onlyname=ftp(ftpads,name,WebRequestMethods.Ftp.ListDirectory);
if(!Directory.Exists(downloadDir))
{
Directory.CreateDirectory(downloadDir);
}
foreach(stringnamesinfullname)
{
//判断是否具有文件夹标识<DIR>
if(names.Contains("<DIR>"))
{
stringolname=names.Split(newstring[]{"<DIR>"},
StringSplitOptions.None)[1].Trim();
downftp(ftpdir,"//"+olname,downloadDir);
}
else
{
foreach(stringonlynamesinonlyname)
{
if(onlynames==""||onlynames==""||names=="")
{
break;
}
else
{
if(names.Contains(""+onlynames))
{
download(downloadDir+"/"+onlynames,ftpads+name+"/"+
onlynames);
break;
}
}
}
}
}
}

}

在使用WebRequestMethods.Ftp.ListDirectoryDetails取得文件夹下所有内容时,会发现如果其中有文件夹,那么文件夹的的详细信息中会有一个"<DIR>"标识,我们就可以通过这个来将其区分开来

同时在获取文件夹以及文件名称时用到WebRequestMethods.Ftp.ListDirectory,这个指令能过只获得文件夹下所有文件包括文件夹的名字,通过这两个指令所获取的信息逐一比较,便能确定出文件或文件夹名以传递到download和downftp方法中

‘叁’ C语言实现从FTP下载、上传文件

FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议”。
1.C语言可以使用CStdioFile函数打开本地文件。使用类CInternetSession 创建并初始化一个Internet打开FTP服务器文件。
CStdioFile继承自CFile,一个CStdioFile 对象代表一个用运行时函数fopen 打开的C 运行时流式文件。
流式文件是被缓冲的,而且可以以文本方式(缺省)或二进制方式打开。文本方式提供对硬回车—换行符对的特殊处理。当你将一个换行符(0x0A)写入一个文本方式的CStdioFile 对象时,字节对(0x0D,0x0A)被发送给该文件。当你读一个文件时,字节对(0x0D,0x0A)被翻译为一个字节(0x0A)。
CStdioFile 不支持Duplicate,LockRange,和UnlockRange 这几个CFile 函数。如果在CStdioFile 中调用了这几个函数,将会出现CNoSupported 异常。
使用类CInternetSession 创建并初始化一个或多个同时的Internet 会话。如果需要,还可描述与代理服务器的连接。
如果Internet连接必须在应用过程中保持着,可创建一个类CWinApp的CInternetSession成员。一旦已建立起Internet 会话,就可调用OpenURL。CInternetSession会通过调用全局函数AfxParseURL来为分析映射URL。无论协议类型如何,CInternetSession 解释URL并管理它。它可处理由URL资源“file://”标志的本地文件的请求。如果传给它的名字是本地文件,OpenURL 将返回一个指向CStdioFile对象的指针。
如果使用OpenURL在Internet服务器上打开一个URL,你可从此处读取信息。如果要执行定位在服务器上的指定的服务(例如,HTTP,FTP或Gopher)行为,必须与此服务器建立适当的连接。

‘肆’ 使用visual c++怎样实现ftp服务器的上传和下载急----

你用用C++的开源库POCO,
只要下面的简单代码就可以实现FTP。。

#include "Poco/Net/FTPClientSession.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/NetException.h"
。。。

using Poco::Net::FTPClientSession;
using Poco::Net::SocketAddress;
using Poco::Net::FTPException;

。。。

FTPClientSession session(host, port);//创建FTP会话对象
session.login(username, password); //登录
session.setWorkingDirectory(path); //转到工作目录
ostream& os= session.beginUpload(fileName);//指定远尺差程文陵察皮件名开始上传
os << "test" ; //上传内容
session.endUpload(); //结束没世上传

‘伍’ 怎么从FTP上下载东西

其实我建议使用一个专门的ftp客户端来使用ftp比较好,这样你只需要在客户端上输入ftp服务器的IP和端口,账号,密码,就能轻松的上传和下载文件,非常实用。

这里我推荐使用IIS7服务器管理工具,它可以作为FTP的客户端,想要进行FTP的上传下载操作,只需要下载安装iis7服务器管理工具就可以了!免费下载,很方便。

同时它还可以作为VNC的客户端,进行VNC的相应操作!它能够连接Windows和Linux系统下的服务器和VPS,能满足你不同系统的使用,感觉不错的话可以试试

‘陆’ 在MFC ftp下载文件的程序中 怎样使用Getfile()下载文件,在远程路径中使用的是URL地址 还是其他什么

请注意第一个参数不支持路径,只支持文件名。下载某个子目录下的文件,需要先用SetCurrentDirectory()进入该文件夹。

‘柒’ c# 从ftp下载文件到本地指定位置

我就给了个1.exe的下载,其它的做尺此循环可以解决
FTP下载衫困陆
/*
using System.IO;
private Stream stream = null;
private StreamReader reader = null;
private FileInfo f= null;
private StreamWriter writer = null;
private char[] c =null;
*/
f = new FileInfo(@"D:\Temp\1.exe");
if(f.Exists() && MessageBox.show("文件已或顷存在,是否重新下载?", "打、打、打劫",MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)==DialogResult.Cancel)
return;
try
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://.com/2010/1.exe");
ftpRequest.Credentials = new NetworkCredential("user", "user");
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
stream = ftpResponse.GetResponseStream();
reader = new StreamReader(stream, Encoding.Default);
writer = f.CreateText();
while (reader.Peek() >= 0)
{
//This is an arbitrary size for this example.
char[] c = new char[5120];
reader.Read(c, 0, c.Length);
writer.Write(c);
}
writer.Flush();
}
catch
{
return "读取FTP文件失败";
}
finally
{
if (reader != null) { reader.Close(); }
if (stream != null) { stream.Close(); }
if (writer != null) { writer.Close(); }
}

‘捌’ 从ftp服务器上下载文件


[code]?php
/**
* 函数名 php_ftp_download
* 功能 从Ftp服务族则器上下载文件
* 入口参数
* filename 欲下载的文件名,含路径
*/
function php_ftp_download($filename) {
$phpftp_host = "ftplocalhost"; // 服务器地兆核棚址
$phpftp_port = 21; // 服务器端口
$phpftp_user = "name"; // 用户名
$phpftp_passwd = "passwrd"; // 口令
$ftp_path = dirname($filename) . "/"; // 获取路径
$select_file = basename($filename); // 获取文件名
$ftp = ftp_connect($phpftp_host,$phpftp_port); // 连接Ftp服务器
if($ftp) {
if(ftp_login($ftp, $phpftp_user, $phpftp_passwd)) { // 登录
if(@ftp_chdir($ftp,$ftp_path)) { // 进入指定路径
$tmpfile = tempnam( getcwd()."/", "temp" ); // 创建唯一的临时文件
if(ftp_get($ftp, $tmpfile, $select_file, FTP_BINARY)) { // 下载指定的文件到临氏悉时文件
ftp_quit( $ftp ); // 关闭连接
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . $select_file);
readfile($tmpfile);
unlink($tmpfile ); // 删除临时文件
exit;
}
unlink($tmpfile );
}
}
}
ftp_quit($ftp);
}
?
[/code][button value="复制代码"]

‘玖’ 写个小程序从FTP上下载文件

从indy clients组件面板中拖一个idftp组件, 然后在按钮中写如下代码 idftp1.host := '192.168.0.1'; //ftp服务器的ip地址 idftp1.username := '***'; //登录ftp服务器的用户名 idftp1.password := '***'; //登录ftp服务器的密码 idftp1.port := '21'; //端口号默认为21,如果不更改则不加此行代码 if IdFTP1.Connected then IdFTP1.Disconnect; begin try IdFTP1.Connect(); except showmessage('FTP链接失败!'); exit; end; end; //开始上传 idftp1.put('需上传文件的目录名','需上传文件的文件名',false); //开始下载 idftp1.get('ftp服务器目录','存放本地目录名',如果文件存在是否覆盖已存在文件,是否重命名文件名);

‘拾’ C#从ftp下载文件如何判断下载结束

从流里读取的字节数为0时,则下载结束。

c#实现绝如 ftp ;http;共享方式下载文件 并对比本地文件和服务器文件的更新时间 判断性下载

//从ftp服务器上下载文件的功能
public void Download(string ftpServerIP, string ftpUserID, string ftpPassword, string fileName, string Destination)
{
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(Destination + "\\" + fileName, FileMode.Create);
// 根据uri创建FtpWebRequest对象行手
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
// 默认为true,连接不会被关闭
reqFTP.UseBinary = true;
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse ftpresponse = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = ftpresponse.GetResponseStream();
long cl = ftpresponse.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
ftpresponse.Close();
}
catch (Exception ex)
{

}
}
//从http服务器上下载文件的功能
//为服务并带启器路径server_path
//本地存储路径local_path
public void Download(string server_path, string local_path)
{
HttpWebRequest req;
try
{
string folder = local_path.Substring(0, local_path.LastIndexOf("\\"));
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
// 根据uri创建FtpWebRequest对象
req = (HttpWebRequest)HttpWebRequest.Create(new Uri(server_path));
// 指定执行什么命令
req.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
if (File.Exists(local_path))
{
FileInfo localFile = new FileInfo(local_path);
if (localFile.LastWriteTime > response.LastModified) return;
}
FileStream outputStream = new FileStream(local_path, FileMode.Create);
Stream stream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = stream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = stream.Read(buffer, 0, bufferSize);
}
stream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
string s = ex.Message;
}
}

//从共享文件夹下载
public void Download(string server_path, string local_path, int i)
{
try
{
server_path = "\\" + server_path;
string folder = local_path.Substring(0, local_path.LastIndexOf("\\"));
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
if (!File.Exists(server_path)) return;

//服务器文件信息
FileInfo serverInfo = new FileInfo(server_path);
DateTime serverTime = serverInfo.LastWriteTime;
if (File.Exists(local_path))
{
FileInfo localinfo = new FileInfo(local_path);
DateTime localTime = localinfo.LastWriteTime;

if (localTime >= serverTime)
return;
}

serverInfo.CopyTo(local_path, true);
return;
}
catch (Exception ex)
{
string s = ex.Message;
}
}