第8章 FTP文件上传下载
- 格式:ppt
- 大小:5.88 MB
- 文档页数:36
详解ftp⽂件上传下载命令介绍:从本地以⽤户wasqry登录的机器1*.1**.21.67上通过ftp远程登录到ftp服务器上,登录⽤户名是lte****,以下为使⽤该连接做的实验。
查看远程ftp服务器上⽤户lte****相应⽬录下的⽂件所使⽤的命令为:ls,登录到ftp后在ftp命令提⽰符下查看本地机器⽤户wasqry相应⽬录下⽂件的命令是:!ls。
查询ftp命令可在提⽰符下输⼊:?,然后回车。
1、从远程ftp服务器下载⽂件的命令格式:get 远程ftp服务器上当前⽬录下要下载的⽂件名 [下载到本地机器上当前⽬录时的⽂件名],如:get nmap_file [nmap]意思是把远程ftp服务器下的⽂件nmap_file下载到本地机器的当前⽬录下,名称更改为nmap。
带括号表⽰可写可不写,不写的话是以该⽂件名下载。
如果要往ftp服务器上上传⽂件的话需要去修改⼀下vsftpd的配置⽂件,名称是vsftpd.conf,在/etc⽬录下。
要把其中的“#write_enable=YES”前⾯的“#”去掉并保存,然后重启vsftpd服务:sudo service vsftpd restart。
2、向远程ftp服务器上传⽂件的命令格式:put/mput 本地机器上当前⽬录下要上传的⽂件名 [上传到远程ftp服务器上当前⽬录时的⽂件名],如:put/mput sample.c [ftp_sample.c]意思是把本地机器当前⽬录下的⽂件smaple.c上传到远程ftp服务器的当前⽬录下,名称更改为ftp_sample.c。
带括号表⽰可写可不写,不写的话是以该⽂件名上传。
如图下download.sh等⽂件本位于该机器linux系统⽬录,通过如下命令,则将linux系统当前⽬录下的download.sh等⽂件上传⾄ftp服务器的当前⽬录3、最后附上ftp常⽤命令,如下所⽰:FTP>open [ftpservername],和指定的远程Linux FTP服务器连接?FTP>user [username] [password],使⽤指定远程Linux FTP服务器的⽤户登录?FTP>pwd,显⽰远程Linux FTP服务器上的当前路径?FTP>ls,列出远程Linux FTP服务器上当前路径下的⽬录和⽂件?FTP>dir,列出远程Linux FTP服务器上当前路径下的⽬录和⽂件(同上)?FTP>mkdir [foldname],在远程Linux FTP服务器上当前路径下建⽴指定⽬录?FTP>rmdir [foldname],删除远程Linux FTP服务器上当前路径下的指定⽬录?FTP>cd [foldname],更改远程Linux FTP服务器上的⼯作⽬录?FTP>delete [filename],删除远程Linux FTP服务器上指定的⽂件?FTP>rename [filename] [newfilename],重命名远程Linux FTP服务器上指定的⽂件?FTP>close,从远程Linux FTP服务器断开但保留FTP命令参数提⽰?FTP>disconnect,从远程Linux FTP服务器断开但保留FTP命令参数提⽰(同上)?FTP>bye,结束和远程Linux FTP服务器的连接。
SFTP⽂件上传下载以及如何处理异常,页⾯展现⾸先需要⼀个第三⽅包,⽹上有很多种⽅式,我这⾥⽤的是ChannelSftpAPI地址 http://epaul.github.io/jsch-documentation/javadoc/com/jcraft/jsch/ChannelSftp.html1.⼯具类/**** @author Caicaizi**/public class SFTPUtils {private static final Logger LOG = LoggerFactory.getLogger(SFTPUtils.class);/*** 打开ssh会话** @param username* @param host* @param port* @param pwd* @return* @throws JSchException*/private static Session openSession(String username, String host, int port, String pwd) throws JSchException {JSch jsch = new JSch();Session session = jsch.getSession(username, host, port);session.setPassword(pwd);Properties config = new Properties();config.put("StrictHostKeyChecking", "no");config.put("PreferredAuthentications", "password");int timeout = 3000;session.setServerAliveInterval(timeout); //session.setConfig(config); // 为Session对象设置propertiessession.setTimeout(timeout); // 设置timeout时间session.connect(); // 通过Session建⽴连接("Session connected.");return session;}/*** 获取⽂件** @param filePath* ⽂件路径* @param out* 输出流* @param username* @param host* @param port* @param pwd*/public static void getFile(String filePath, OutputStream out, String username, String host, int port, String pwd) {ChannelSftp channel = null;Session session = null;try {session = openSession(username, host, port, pwd);("Opening channel");channel = (ChannelSftp) session.openChannel("sftp");channel.connect();channel.get(filePath, out);} catch (JSchException e) {LOG.error("连接服务器失败", e);} catch (SftpException e) {LOG.error("⽂件获取失败", e);} finally {close(channel, session);}}public static void uploadFile(InputStream input, String filename, String path, String username, String host,int port, String pwd) {ChannelSftp channel = null;Session session = null;try {session = openSession(username, host, port, pwd);channel = (ChannelSftp) session.openChannel("sftp");channel.connect();SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");String date = format.format(new Date());channel.cd(path);// 查看⽇期对应的⽬录状态try {channel.stat(date);} catch (Exception e) {("⽬录不存在,创建⽬录:" + path + "/" + date);channel.mkdir(date);}channel.put(input,path+"/"+date+"/"+filename);} catch (JSchException e) {LOG.error("连接服务器失败", e);} catch (SftpException e) {LOG.error("⽂件上传失败", e);} finally{close(channel, session);}}/*** 释放sftp连接资源** @param channel* @param session*/private static void close(ChannelSftp channel, Session session) {if (channel != null) {channel.quit();channel.disconnect();}if (session != null) {session.disconnect();}}} 我们所需要的参数必须:IP,PORT,路径,⽂件名,以及账号密码;上传⽂件可以直接调⽤:uploadFile,下载:getFile。
LeapFtp可以说是一款功能强大的FTP软件,友好的用户界面,稳定的传输速度,拥有跟Netscape相仿的书签形式,连接更加方便。
支持断点续传功能,可以下载或上传整个目录,亦可直接删除整个目录,可让你设置队列一次下载或上传同一站点中不同目录下的文件,是南昌网站优化必备的软件,同时还具有不会因闲置过久而被远程FTP服务器踢出的功能。
并可直接编辑远端Server上的文件,还可设定文件传送完毕自动中断Modem连接等。
名词解释:【FTP】FTP是英文File Transfer Protocol的缩写,也就是文件传输协议的意思。
是TCP/IP 协议组中的协议之一,该协议是Internet文件传送的基础,它由一系列规格说明文档组成。
使得用户可以通过FTP功能登录到远程计算机,从其它计算机系统中下载需要的文件或将自己的文件上传到网络上。
第一:下载安装软件下载后为一个.exe格式的文件。
无需安装,可以直接双击运行。
第二:界面预览LeapFtp主界面默认显示了本地目录、远程目录、队列及状态四大窗口。
第三:站点设置要使用FTP工具来上传(下载)文件,首先必须要设定好FTP服务器的网址(IP地址)、授权访问的用户名及密码。
下面我们将演示具体的参数设置,看完之后即使是初入门的菜鸟级用户也能很快上手,哈哈。
通过菜单【站点】—>【站点管理器】或者F4键我们可以对要连接的远程FTP服务器进行具体的设置。
第一步:我们可以点击【添加站点】按钮,输入站点的名称(它只是对FTP站点的一个说明)。
第二步:按照界面所示,首先去掉匿名选项(匿名的意思就是不需要用户名和密码可以直接访问FTP服务器,但很多FTP服务器都禁止匿名访问),然后分别输入IP地址(FTP服务器所拥有的IP),用户名和密码(如果你不知道的话,可以询问提供FTP服务的运营商或管理员)。
另外对于端口号我们在没有特别要求的情况下就使用默认的端口号(21),不必在进行改变。
ftp⽂件操作类(上传、下载、删除、创建、重命名、获取⽬录中的所有⽂件)ftp⽂件操作类1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using ;6using System.IO;7using System.Data;8using ponentModel;9using System.Windows.Forms;10using System.Text.RegularExpressions;11using System.Globalization;12using System.Collections;1314namespace ESIMRobot15 {16#region⽂件信息结构17public struct FileStruct18 {19public string Flags;20public string Owner;21public string Group;22public bool IsDirectory;23public DateTime CreateTime;24public string Name;25 }26public enum FileListStyle27 {28 UnixStyle,29 WindowsStyle,30 Unknown31 }32#endregion3334///<summary>35/// ftp⽂件上传、下载操作类36///</summary>37public class FTPHelper38 {39private string ftpServerURL;40private string ftpUser;41private string ftpPassWord;4243///<summary>44///45///</summary>46///<param name="ftpServerURL">ftp服务器路径</param>47///<param name="ftpUser">ftp⽤户名</param>48///<param name="ftpPassWord">ftp⽤户名</param>49public FTPHelper(string ftpServerURL, string ftpUser, string ftpPassWord)50 {51this.ftpServerURL = ftpServerURL;52this.ftpUser = ftpUser;53this.ftpPassWord = ftpPassWord;54 }55///<summary>56///通过⽤户名,密码连接到FTP服务器57///</summary>58///<param name="ftpUser">ftp⽤户名,匿名为“”</param>59///<param name="ftpPassWord">ftp登陆密码,匿名为“”</param>60public FTPHelper(string ftpUser, string ftpPassWord)61 {62this.ftpUser = ftpUser;63this.ftpPassWord = ftpPassWord;64 }6566///<summary>67///匿名访问68///</summary>69public FTPHelper(string ftpURL)70 {71this.ftpUser = "";72this.ftpPassWord = "";73 }747576//**************************************************** Start_1 *********************************************************//77///<summary>78///从FTP下载⽂件到本地服务器,⽀持断点下载79///</summary>80///<param name="ftpFilePath">ftp⽂件路径,如"ftp://localhost/test.txt"</param>81///<param name="saveFilePath">保存⽂件的路径,如C:\\test.txt</param>82public void BreakPointDownLoadFile(string ftpFilePath, string saveFilePath)83 {84 System.IO.FileStream fs = null;85 .FtpWebResponse ftpRes = null;86 System.IO.Stream resStrm = null;87try88 {89//下载⽂件的URI90 Uri uri = new Uri(ftpFilePath);91//设定下载⽂件的保存路径92string downFile = saveFilePath;9394//FtpWebRequest的作成95 .FtpWebRequest ftpReq = (.FtpWebRequest)96 .WebRequest.Create(uri);97//设定⽤户名和密码98 ftpReq.Credentials = new workCredential(ftpUser, ftpPassWord);99//MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定100 ftpReq.Method = .WebRequestMethods.Ftp.DownloadFile;101//要求终了后关闭连接102 ftpReq.KeepAlive = false;103//使⽤ASCII⽅式传送104 eBinary = false;105//设定PASSIVE⽅式⽆效106 ePassive = false;107108//判断是否继续下载109//继续写⼊下载⽂件的FileStream110if (System.IO.File.Exists(downFile))111 {112//继续下载113 ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;114 fs = new System.IO.FileStream(115 downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);116 }117else118 {119//⼀般下载120 fs = new System.IO.FileStream(121 downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);122 }123124//取得FtpWebResponse125 ftpRes = (.FtpWebResponse)ftpReq.GetResponse();126//为了下载⽂件取得Stream127 resStrm = ftpRes.GetResponseStream();128//写⼊下载的数据129byte[] buffer = new byte[1024];130while (true)131 {132int readSize = resStrm.Read(buffer, 0, buffer.Length);133if (readSize == 0)134break;135 fs.Write(buffer, 0, readSize);136 }137 }138catch (Exception ex)139 {140throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + ftpFilePath + "异常信息:" + ex.ToString()); 141 }142finally143 {144 fs.Close();145 resStrm.Close();146 ftpRes.Close();147 }148 }149150151#region152//从FTP上下载整个⽂件夹,包括⽂件夹下的⽂件和⽂件夹函数列表153154///<summary>155///从ftp下载⽂件到本地服务器156///</summary>157///<param name="ftpFilePath">要下载的ftp⽂件路径,如ftp://192.168.1.104/capture-2.avi</param>158///<param name="saveFilePath">本地保存⽂件的路径,如(@"d:\capture-22.avi"</param>159public void DownLoadFile(string ftpFilePath, string saveFilePath)160 {161 Stream responseStream = null;162 FileStream fileStream = null;163 StreamReader reader = null;164try165 {166// string downloadUrl = "ftp://192.168.1.104/capture-2.avi";167 FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(ftpFilePath);168 downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;169 downloadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);170 FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();171 responseStream = downloadResponse.GetResponseStream();172173 fileStream = File.Create(saveFilePath);174byte[] buffer = new byte[1024];175int bytesRead;176while (true)177 {178 bytesRead = responseStream.Read(buffer, 0, buffer.Length);179if (bytesRead == 0)180break;181 fileStream.Write(buffer, 0, bytesRead);182 }183 }184catch (Exception ex)185 {186throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + ftpFilePath + "异常信息:" + ex.ToString()); 187 }188finally189 {190if (reader != null)191 {192 reader.Close();193 }194if (responseStream != null)195 {196 responseStream.Close();197 }198if (fileStream != null)199 {200 fileStream.Close();201 }202 }203 }204205206///<summary>207///列出当前⽬录下的所有⽂件和⽬录208///</summary>209///<param name="ftpDirPath">FTP⽬录</param>210///<returns></returns>211public List<FileStruct> ListCurrentDirFilesAndChildDirs(string ftpDirPath)212 {213 WebResponse webresp = null;214 StreamReader ftpFileListReader = null;215 FtpWebRequest ftpRequest = null;216try217 {218 ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirPath));219 ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;220 ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);221 webresp = ftpRequest.GetResponse();222 ftpFileListReader = new StreamReader(webresp.GetResponseStream(),Encoding.GetEncoding("UTF-8")); 223 }224catch (Exception ex)225 {226throw new Exception("获取⽂件列表出错,错误信息如下:" + ex.ToString());227 }228string Datastring = ftpFileListReader.ReadToEnd();229return GetListX(Datastring);230231 }232233///<summary>234///列出当前⽬录下的所有⽂件235///</summary>236///<param name="ftpDirPath">FTP⽬录</param>237///<returns></returns>238public List<FileStruct> ListCurrentDirFiles(string ftpDirPath)239 {240 List<FileStruct> listAll = ListCurrentDirFilesAndChildDirs(ftpDirPath);241 List<FileStruct> listFile = new List<FileStruct>();242foreach (FileStruct file in listAll)243 {244if (!file.IsDirectory)245 {246 listFile.Add(file);247 }248 }249return listFile;250 }251252253///<summary>254///列出当前⽬录下的所有⼦⽬录255///</summary>256///<param name="ftpDirath">FRTP⽬录</param>257///<returns>⽬录列表</returns>258public List<FileStruct> ListCurrentDirChildDirs(string ftpDirath)259 {260 List<FileStruct> listAll = ListCurrentDirFilesAndChildDirs(ftpDirath);261 List<FileStruct> listDirectory = new List<FileStruct>();262foreach (FileStruct file in listAll)263 {264if (file.IsDirectory)265 {266 listDirectory.Add(file);267 }268 }269return listDirectory;270 }271272273///<summary>274///获得⽂件和⽬录列表(返回类型为: List<FileStruct> )275///</summary>276///<param name="datastring">FTP返回的列表字符信息</param>277private List<FileStruct> GetListX(string datastring)278 {279 List<FileStruct> myListArray = new List<FileStruct>();280string[] dataRecords = datastring.Split('\n');281 FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);282foreach (string s in dataRecords)283 {284if (_directoryListStyle != FileListStyle.Unknown && s != "")285 {286 FileStruct f = new FileStruct();287 = "..";288switch (_directoryListStyle)289 {290case FileListStyle.UnixStyle:291 f = ParseFileStructFromUnixStyleRecord(s);292break;293case FileListStyle.WindowsStyle:294 f = ParseFileStructFromWindowsStyleRecord(s);295break;296 }297if (!( == "." || == ".."))298 {299 myListArray.Add(f);300 }301 }302 }303return myListArray;304 }305///<summary>306///从Unix格式中返回⽂件信息307///</summary>308///<param name="Record">⽂件信息</param>309private FileStruct ParseFileStructFromUnixStyleRecord(string Record)310 {311 FileStruct f = new FileStruct();312string processstr = Record.Trim();313 f.Flags = processstr.Substring(0, 10);314 f.IsDirectory = (f.Flags[0] == 'd');315 processstr = (processstr.Substring(11)).Trim();316 cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分317 f.Owner = cutSubstringFromStringWithTrim(ref processstr, '', 0);318 f.Group = cutSubstringFromStringWithTrim(ref processstr, '', 0);319 cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分320string yearOrTime = processstr.Split(new char[] { '' }, StringSplitOptions.RemoveEmptyEntries)[2]; 321if (yearOrTime.IndexOf(":") >= 0) //time322 {323 processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());324 }325 f.CreateTime = DateTime.Parse(cutSubstringFromStringWithTrim(ref processstr, '', 8));326 = processstr; //最后就是名称327return f;328 }329330///<summary>331///从Windows格式中返回⽂件信息332///</summary>333///<param name="Record">⽂件信息</param>334private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)335 {336 FileStruct f = new FileStruct();337string processstr = Record.Trim();338string dateStr = processstr.Substring(0, 8);339 processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();340string timeStr = processstr.Substring(0, 7);341 processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();342 DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;343 myDTFI.ShortTimePattern = "t";344 f.CreateTime = DateTime.Parse(dateStr + "" + timeStr, myDTFI);345if (processstr.Substring(0, 5) == "<DIR>")346 {347 f.IsDirectory = true;348 processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();349 }350else351 {352string[] strs = processstr.Split(new char[] { '' }, 2);// StringSplitOptions.RemoveEmptyEntries); // true); 353 processstr = strs[1];354 f.IsDirectory = false;355 }356 = processstr;357return f;358 }359360361///<summary>362///按照⼀定的规则进⾏字符串截取363///</summary>364///<param name="s">截取的字符串</param>365///<param name="c">查找的字符</param>366///<param name="startIndex">查找的位置</param>367private string cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)368 {369int pos1 = s.IndexOf(c, startIndex);370string retString = s.Substring(0, pos1);371 s = (s.Substring(pos1)).Trim();372return retString;373 }374375376///<summary>377///判断⽂件列表的⽅式Window⽅式还是Unix⽅式378///</summary>379///<param name="recordList">⽂件信息列表</param>380private FileListStyle GuessFileListStyle(string[] recordList)381 {382foreach (string s in recordList)383 {384if (s.Length > 10385 && Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))386 {387return FileListStyle.UnixStyle;388 }389else if (s.Length > 8390 && Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))391 {392return FileListStyle.WindowsStyle;393 }394 }395return FileListStyle.Unknown;396 }397398399///<summary>400///从FTP下载整个⽂件夹401///</summary>402///<param name="ftpDirPath">FTP⽂件夹路径</param>403///<param name="saveDirPath">保存的本地⽂件夹路径</param>404///调⽤实例: DownFtpDir("FTP://192.168.1.113/WangJin", @"C:\QMDownload\SoftMgr");405///当调⽤的时候先判断saveDirPath的⼦⽬录中是否有WangJin⽬录,有则执⾏,没有创建后执⾏406///最终⽂件保存在@"C:\QMDownload\SoftMgr\WangJin"下407public bool DownFtpDir(string ftpDirPath, string saveDirPath)408 {409bool success = true;410try411 {412 List<FileStruct> files = ListCurrentDirFilesAndChildDirs(ftpDirPath);413if (!Directory.Exists(saveDirPath))414 {415 Directory.CreateDirectory(saveDirPath);416 }417foreach (FileStruct f in files)418 {419if (f.IsDirectory) //⽂件夹,递归查询421 DownFtpDir(ftpDirPath + "/" + , saveDirPath + "\\" + );422 }423else//⽂件,直接下载424 {425 DownLoadFile(ftpDirPath + "/" + , saveDirPath + "\\" + );426 }427 }428 }429catch (Exception e)430 {431 MessageBox.Show(e.Message);432 success = false;433 }434return success;435 }436#endregion437438439440///<summary>441///列出当前⽬录下的所有⼦⽬录和⽂件到TreeView控件中442///</summary>443///<param name="ftpDirPath"> FTP服务器⽬录</param>444///<param name="treeview">显⽰到TreeView控件中</param>445///<param name="treenode">TreeView控件的⼦节点</param>446public void ListCurrentDirFilesAndDirToTreeView(string ftpDirPath, TreeView treeview, TreeNode treenode) 447 {448if (ftpDirPath == "")449 {450 ftpDirPath = ftpServerURL;451 }452if (treeview != null)453 {454 treeview.Nodes.Clear();455 treenode = treeview.Nodes.Add(ftpDirPath);456 }457 List<FileStruct> files = ListCurrentDirFilesAndChildDirs(ftpDirPath);458foreach (FileStruct f in files)459 {460if (f.IsDirectory) //如果为⽬录(⽂件夹),递归调⽤461 {462 TreeNode td = treenode.Nodes.Add();463 ListCurrentDirFilesAndDirToTreeView(ftpDirPath + "/" + , null, td);464 }465else//如果为⽂件,直接加⼊到节点中466 {467 treenode.Nodes.Add();468 }469 }470 }471//************************************* End_1 ****************************//472473474475476//************************************ Start_2 ***************************//477///<summary>478///检测⽂件或⽂件⽬录是否存在479///</summary>480///<param name="ftpDirPath">ftp服务器中的⽬录路径</param>481///<param name="ftpDirORFileName">待检测的⽂件或⽂件名</param>482///<returns></returns>483///操作实例: ftpclient.fileOrDirCheckExist("FTP://192.168.1.113/Record/", "")484/// ftpclient.fileOrDirCheckExist("FTP://192.168.1.113/RecordFile/", "333.txt")485public bool fileOrDirCheckExist(string ftpDirPath, string ftpDirORFileName)486 {487bool success = true;488 FtpWebRequest ftpWebRequest = null;489 WebResponse webResponse = null;490 StreamReader reader = null;491try492 {493string url = ftpDirPath + ftpDirORFileName;494 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));495 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);496 ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;497 ftpWebRequest.KeepAlive = false;498 webResponse = ftpWebRequest.GetResponse();499 reader = new StreamReader(webResponse.GetResponseStream());500string line = reader.ReadLine();501while (line != null)502 {503if (line == ftpDirORFileName)504 {505break;507 line = reader.ReadLine();508 }509 }510catch (Exception)511 {512 success = false;513 }514finally515 {516if (reader != null)517 {518 reader.Close();519 }520if (webResponse != null)521 {522 webResponse.Close();523 }524 }525return success;526 }527528529///<summary>530///获得⽂件和⽬录列表(返回类型为:FileStruct)531///</summary>532///<param name="datastring">FTP返回的列表字符信息</param>533public FileStruct GetList(string datastring)534 {535 FileStruct f = new FileStruct();536string[] dataRecords = datastring.Split('\n');537 FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);538if (_directoryListStyle != FileListStyle.Unknown && datastring != "")539 {540541switch (_directoryListStyle)542 {543case FileListStyle.UnixStyle:544 f = ParseFileStructFromUnixStyleRecord(datastring);545break;546case FileListStyle.WindowsStyle:547 f = ParseFileStructFromWindowsStyleRecord(datastring);548break;549 }550 }551return f;552 }553554555///<summary>556///上传557///</summary>558///<param name="localFilePath">本地⽂件名路径</param>559///<param name="ftpDirPath">上传到ftp中⽬录的路径</param>560///<param name="ftpFileName">上传到ftp中⽬录的⽂件名</param>561///<param name="fileLength">限制上传⽂件的⼤⼩(Bytes为单位)</param>562///操作实例: ftpclient.fileUpload(@"E:\bin\Debug\Web\RecordFile\wangjin\wangjin.txt", "FTP://192.168.1.113/Record/","123.txt",0 );563public bool UploadFile(FileInfo localFilePath, string ftpDirPath, string ftpFileName, long fileLength)564 {565bool success = true;566long filesize = 0;567 FtpWebRequest ftpWebRequest = null;568 FileStream localFileStream = null;569 Stream requestStream = null;570if (fileLength > 0)571 {572 filesize = fileLength * 1024 * 1024;573 }574if (localFilePath.Length <= filesize || filesize == 0)575 {576if (fileOrDirCheckExist(ftpDirPath.Substring(0, stIndexOf(@"/") + 1), ftpDirPath.Substring(stIndexOf(@"/") + 1))) 577 {578try579 {580string uri = ftpDirPath + ftpFileName;581 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));582 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);583 eBinary = true;584 ftpWebRequest.KeepAlive = false;585 ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;586 ftpWebRequest.ContentLength = localFilePath.Length;587int buffLength = 2048; //定义缓存⼤⼩2KB588byte[] buff = new byte[buffLength];589int contentLen;590 localFileStream = localFilePath.OpenRead();591 requestStream = ftpWebRequest.GetRequestStream();592 contentLen = localFileStream.Read(buff, 0, buffLength);593while (contentLen != 0)594 {595 requestStream.Write(buff, 0, contentLen);596 contentLen = localFileStream.Read(buff, 0, buffLength);597 }598 }599catch (Exception)600 {601 success = false;602 }603finally604 {605if (requestStream != null)606 {607 requestStream.Close();608 }609if (localFileStream != null)610 {611 localFileStream.Close();612 }613 }614 }615else616 {617 success = false;618 MessageBox.Show("FTP⽂件路径不存在!");619 }620 }621else622 {623 success = false;624 MessageBox.Show("⽂件⼤⼩超过设置范围!" + "\n" + "⽂件实际⼤⼩为:" + localFilePath.Length + "\n" + "允许上传阈值为:" + (5 * 1024 * 1024).ToString()); 625 }626return success;627 }628629///<summary>630///下载⽂件631///</summary>632///<param name="ftpFilePath">需要下载的⽂件名路径</param>633///<param name="localFilePath">本地保存的⽂件名路径)</param>634///操作实例: ftpclient.fileDownload(@"E:\bin\Debug\Web\RecordFile\wangjin\459.txt", "FTP://192.168.1.113/Record/123.txt");635public bool DownloadFile( string localFilePath, string ftpFilePath)636 {637bool success = true;638 FtpWebRequest ftpWebRequest = null;639 FtpWebResponse ftpWebResponse = null;640 Stream ftpResponseStream = null;641 FileStream outputStream = null;642try643 {644 outputStream = new FileStream(localFilePath, FileMode.Create);645string uri = ftpFilePath;646 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));647 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);648 eBinary = true;649 ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;650 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();651 ftpResponseStream = ftpWebResponse.GetResponseStream();652long contentLength = ftpWebResponse.ContentLength;653int bufferSize = 2048;654byte[] buffer = new byte[bufferSize];655int readCount;656 readCount = ftpResponseStream.Read(buffer, 0, bufferSize);657while (readCount > 0)658 {659 outputStream.Write(buffer, 0, readCount);660 readCount = ftpResponseStream.Read(buffer, 0, bufferSize);661 }662 }663catch (Exception)664 {665 success = false;666 }667finally668 {669if (outputStream != null)670 {671 outputStream.Close();672 }673if (ftpResponseStream != null)674 {675 ftpResponseStream.Close();676 }677if (ftpWebResponse != null)679 ftpWebResponse.Close();680 }681 }682return success;683 }684685686///<summary>687///重命名688///</summary>689///<param name="ftpDirPath">ftp服务器中的⽬录</param>690///<param name="currentFilename">当前要修改的⽂件名</param>691///<param name="newFilename">修改后的新⽂件名</param>692///操作实例: ftpclientxy.fileRename("FTP://192.168.1.113/RecordFile/", "123.txt", "333.txt");693public bool RenameFile(string ftpDirPath, string currentFileName, string newFileName)694 {695bool success = true;696 FtpWebRequest ftpWebRequest = null;697 FtpWebResponse ftpWebResponse = null;698 Stream ftpResponseStream = null;699if (fileOrDirCheckExist(ftpDirPath.Substring(0, stIndexOf(@"/") + 1), ftpDirPath.Substring(stIndexOf(@"/") + 1))) 700 {701try702 {703string uri = ftpDirPath + currentFileName;704 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));705 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);706 eBinary = true;707 ftpWebRequest.Method = WebRequestMethods.Ftp.Rename;708 ftpWebRequest.RenameTo = newFileName;709 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();710 ftpResponseStream = ftpWebResponse.GetResponseStream();711 }712catch (Exception)713 {714 success = false;715 }716finally717 {718if (ftpResponseStream != null)719 {720 ftpResponseStream.Close();721 }722if (ftpWebResponse != null)723 {724 ftpWebResponse.Close();725 }726 }727 }728else729 {730 success = false;731 MessageBox.Show("FTP⽂件路径不存在!");732 }733return success;734 }735736///<summary>737///在⽬录下创建⼦⽬录738///</summary>739///<param name="ftpDirPath">ftp服务器中的⽬录</param>740///<param name="ftpFileDir">待创建的⼦⽬录</param>741///<returns></returns>742///操作实例: ftpclient.fileDirMake("FTP://192.168.1.113/RecordFile/", "WangJinFile")743public bool MakeDir(string ftpDirPath, string ftpFileDir)744 {745bool success = true;746 FtpWebRequest ftpWebRequest = null;747 WebResponse webResponse = null;748 StreamReader reader = null;749try750 {751string url = ftpDirPath + ftpFileDir;752 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));753// 指定数据传输类型754 eBinary = true;755 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);756 ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;757 webResponse = ftpWebRequest.GetResponse();758 }759catch (Exception)760 {761 success = false;762 }763finally765if (reader != null)766 {767 reader.Close();768 }769if (webResponse != null)770 {771 webResponse.Close();772 }773 }774return success;775 }776777778///<summary>779///删除⽬录中的⽂件780///</summary>781///<param name="ftpDirPath"></param>782///<param name="ftpFileName"></param>783///<returns></returns>784///操作实例: ftpclient.fileDelete("FTP://192.168.1.113/RecordFile/WangJinFile/", "333.txt")785public bool DeleteFile(string ftpDirPath, string ftpFileName)786 {787bool success = true;788 FtpWebRequest ftpWebRequest = null;789 FtpWebResponse ftpWebResponse = null;790 Stream ftpResponseStream = null;791 StreamReader streamReader = null;792try793 {794string uri = ftpDirPath + ftpFileName;795 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));796 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);797 ftpWebRequest.KeepAlive = false;798 ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;799 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();800long size = ftpWebResponse.ContentLength;801 ftpResponseStream = ftpWebResponse.GetResponseStream();802 streamReader = new StreamReader(ftpResponseStream);803string result = String.Empty;804 result = streamReader.ReadToEnd();805 }806catch (Exception)807 {808 success = false;809 }810finally811 {812if (streamReader != null)813 {814 streamReader.Close();815 }816if (ftpResponseStream != null)817 {818 ftpResponseStream.Close();819 }820if (ftpWebResponse != null)821 {822 ftpWebResponse.Close();823 }824 }825return success;826 }827828///<summary>829///获取⽬录的⼦⽬录数组830///</summary>831///<param name="ftpDirPath"></param>832///<returns></returns>833///操作实例: string []filedir = ftpclient.GetDeleteFolderArray("FTP://192.168.1.113/WangJinFile/"); 834public string[] GetDirArray(string ftpDirPath)835 {836string[] deleteFolders;837 FtpWebRequest ftpWebRequest = null;838 FtpWebResponse ftpWebResponse = null;839 Stream ftpResponseStream = null;840 StreamReader streamReader = null;841 StringBuilder result = new StringBuilder();842try843 {844 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpDirPath));845 eBinary = true;846 ePassive = false;847 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);848 ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;849 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();。
C#-FTP递归下载⽂件c# ftp递归下载⽂件,找来找去这个最好。
(打断点,⼀⼩处foreach要改成for)///<summary>/// ftp⽂件上传、下载操作类///</summary>public class FTPHelper{///<summary>/// ftp⽤户名,匿名为“”///</summary>private string ftpUser;///<summary>/// ftp⽤户密码,匿名为“”///</summary>private string ftpPassWord;///<summary>///通过⽤户名,密码连接到FTP服务器///</summary>///<param name="ftpUser">ftp⽤户名,匿名为“”</param>///<param name="ftpPassWord">ftp登陆密码,匿名为“”</param>public FTPHelper(string ftpUser, string ftpPassWord){this.ftpUser = ftpUser;this.ftpPassWord = ftpPassWord;}///<summary>///匿名访问///</summary>public FTPHelper(){this.ftpUser = "";this.ftpPassWord = "";}///<summary>///上传⽂件到Ftp服务器///</summary>///<param name="uri">把上传的⽂件保存为ftp服务器⽂件的uri,如"ftp://192.168.1.104/capture-212.avi"</param> ///<param name="upLoadFile">要上传的本地的⽂件路径,如D:\capture-2.avi</param>public void UpLoadFile(string UpLoadUri, string upLoadFile){Stream requestStream = null;FileStream fileStream = null;FtpWebResponse uploadResponse = null;try{Uri uri = new Uri(UpLoadUri);FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;uploadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);requestStream = uploadRequest.GetRequestStream();fileStream = File.Open(upLoadFile, FileMode.Open);byte[] buffer = new byte[1024];int bytesRead;while (true){bytesRead = fileStream.Read(buffer, 0, buffer.Length);if (bytesRead == 0)break;requestStream.Write(buffer, 0, bytesRead);}requestStream.Close();uploadResponse = (FtpWebResponse)uploadRequest.GetResponse();}catch (Exception ex){throw new Exception("上传⽂件到ftp服务器出错,⽂件名:" + upLoadFile + "异常信息:" + ex.ToString()); }finally{if (uploadResponse != null)uploadResponse.Close();if (fileStream != null)fileStream.Close();if (requestStream != null)requestStream.Close();}}///<summary>///从ftp下载⽂件到本地服务器///</summary>///<param name="downloadUrl">要下载的ftp⽂件路径,如ftp://192.168.1.104/capture-2.avi</param>///<param name="saveFileUrl">本地保存⽂件的路径,如(@"d:\capture-22.avi"</param>public void DownLoadFile(string downloadUrl, string saveFileUrl){Stream responseStream = null;FileStream fileStream = null;StreamReader reader = null;try{// string downloadUrl = "ftp://192.168.1.104/capture-2.avi";FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(downloadUrl);downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;//string ftpUser = "yoyo";//string ftpPassWord = "123456";downloadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();responseStream = downloadResponse.GetResponseStream();fileStream = File.Create(saveFileUrl);byte[] buffer = new byte[1024];int bytesRead;while (true){bytesRead = responseStream.Read(buffer, 0, buffer.Length);if (bytesRead == 0)break;fileStream.Write(buffer, 0, bytesRead);}}catch (Exception ex){throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + downloadUrl + "异常信息:" + ex.ToString()); }finally{if (reader != null){reader.Close();}if (responseStream != null){responseStream.Close();}if (fileStream != null){fileStream.Close();}}}///<summary>///从FTP下载⽂件到本地服务器,⽀持断点下载///</summary>///<param name="ftpUri">ftp⽂件路径,如"ftp://localhost/test.txt"</param>///<param name="saveFile">保存⽂件的路径,如C:\\test.txt</param>public void BreakPointDownLoadFile(string ftpUri, string saveFile){System.IO.FileStream fs = null;.FtpWebResponse ftpRes = null;System.IO.Stream resStrm = null;try{//下载⽂件的URIUri u = new Uri(ftpUri);//设定下载⽂件的保存路径string downFile = saveFile;//FtpWebRequest的作成.FtpWebRequest ftpReq = (.FtpWebRequest).WebRequest.Create(u);//设定⽤户名和密码ftpReq.Credentials = new workCredential(ftpUser, ftpPassWord);//MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定ftpReq.Method = .WebRequestMethods.Ftp.DownloadFile;//要求终了后关闭连接ftpReq.KeepAlive = false;//使⽤ASCII⽅式传送eBinary = false;//设定PASSIVE⽅式⽆效ePassive = false;//判断是否继续下载//继续写⼊下载⽂件的FileStreamif (System.IO.File.Exists(downFile)){//继续下载ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;fs = new System.IO.FileStream(downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);}else{//⼀般下载fs = new System.IO.FileStream(downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);}//取得FtpWebResponseftpRes = (.FtpWebResponse)ftpReq.GetResponse();//为了下载⽂件取得StreamresStrm = ftpRes.GetResponseStream();//写⼊下载的数据byte[] buffer = new byte[1024];while (true){int readSize = resStrm.Read(buffer, 0, buffer.Length);if (readSize == 0)break;fs.Write(buffer, 0, readSize);}}catch (Exception ex){throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + ftpUri + "异常信息:" + ex.ToString()); }finally{fs.Close();resStrm.Close();ftpRes.Close();}}#region从FTP上下载整个⽂件夹,包括⽂件夹下的⽂件和⽂件夹///<summary>///列出FTP服务器上⾯当前⽬录的所有⽂件和⽬录///</summary>///<param name="ftpUri">FTP⽬录</param>///<returns></returns>public List<FileStruct> ListFilesAndDirectories(string ftpUri){WebResponse webresp = null;StreamReader ftpFileListReader = null;FtpWebRequest ftpRequest = null;try{ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpUri));ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);webresp = ftpRequest.GetResponse();ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.Default);}catch (Exception ex){throw new Exception("获取⽂件列表出错,错误信息如下:" + ex.ToString());}string Datastring = ftpFileListReader.ReadToEnd();return GetList(Datastring);}///<summary>///列出FTP⽬录下的所有⽂件///</summary>///<param name="ftpUri">FTP⽬录</param>///<returns></returns>public List<FileStruct> ListFiles(string ftpUri){List<FileStruct> listAll = ListFilesAndDirectories(ftpUri);List<FileStruct> listFile = new List<FileStruct>();foreach (FileStruct file in listAll){if (!file.IsDirectory){listFile.Add(file);}}return listFile;}///<summary>///列出FTP⽬录下的所有⽬录///</summary>///<param name="ftpUri">FRTP⽬录</param>///<returns>⽬录列表</returns>public List<FileStruct> ListDirectories(string ftpUri){List<FileStruct> listAll = ListFilesAndDirectories(ftpUri);List<FileStruct> listDirectory = new List<FileStruct>();foreach (FileStruct file in listAll){if (file.IsDirectory){listDirectory.Add(file);}}return listDirectory;}///<summary>///获得⽂件和⽬录列表///</summary>///<param name="datastring">FTP返回的列表字符信息</param>private List<FileStruct> GetList(string datastring){List<FileStruct> myListArray = new List<FileStruct>();string[] dataRecords = datastring.Split('\n');FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);foreach (string s in dataRecords){if (_directoryListStyle != FileListStyle.Unknown && s != ""){FileStruct f = new FileStruct(); = "..";switch (_directoryListStyle){case FileListStyle.UnixStyle:f = ParseFileStructFromUnixStyleRecord(s);break;case FileListStyle.WindowsStyle:f = ParseFileStructFromWindowsStyleRecord(s);break;}if (!( == "." || == "..")){myListArray.Add(f);}}}return myListArray;}///<summary>///从Unix格式中返回⽂件信息///</summary>///<param name="Record">⽂件信息</param>private FileStruct ParseFileStructFromUnixStyleRecord(string Record) {FileStruct f = new FileStruct();string processstr = Record.Trim();f.Flags = processstr.Substring(0, 10);f.IsDirectory = (f.Flags[0] == 'd');processstr = (processstr.Substring(11)).Trim();_cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分f.Owner = _cutSubstringFromStringWithTrim(ref processstr, '', 0);f.Group = _cutSubstringFromStringWithTrim(ref processstr, '', 0);_cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分string yearOrTime = processstr.Split(new char[] { '' }, StringSplitOptions.RemoveEmptyEntries)[2];if (yearOrTime.IndexOf(":") >= 0) //time{processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());}f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, '', 8)); = processstr; //最后就是名称return f;}///<summary>///从Windows格式中返回⽂件信息///</summary>///<param name="Record">⽂件信息</param>private FileStruct ParseFileStructFromWindowsStyleRecord(string Record){FileStruct f = new FileStruct();string processstr = Record.Trim();string dateStr = processstr.Substring(0, 8);processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();string timeStr = processstr.Substring(0, 7);processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;myDTFI.ShortTimePattern = "t";f.CreateTime = DateTime.Parse(dateStr + "" + timeStr, myDTFI);if (processstr.Substring(0, 5) == "<DIR>"){f.IsDirectory = true;processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();}else{string[] strs = processstr.Split(new char[] { '' },2);// StringSplitOptions.RemoveEmptyEntries); // true); processstr = strs[1];f.IsDirectory = false;} = processstr;return f;}///<summary>///按照⼀定的规则进⾏字符串截取///</summary>///<param name="s">截取的字符串</param>///<param name="c">查找的字符</param>///<param name="startIndex">查找的位置</param>private string _cutSubstringFromStringWithTrim(ref string s, char c, int startIndex){int pos1 = s.IndexOf(c, startIndex);string retString = s.Substring(0, pos1);s = (s.Substring(pos1)).Trim();return retString;}///<summary>///判断⽂件列表的⽅式Window⽅式还是Unix⽅式///</summary>///<param name="recordList">⽂件信息列表</param>private FileListStyle GuessFileListStyle(string[] recordList){foreach (string s in recordList){if (s.Length > 10&& Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)")){return FileListStyle.UnixStyle;}else if (s.Length > 8&& Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]")){return FileListStyle.WindowsStyle;}}return FileListStyle.Unknown;}///<summary>///从FTP下载整个⽂件夹///</summary>///<param name="ftpDir">FTP⽂件夹路径</param>///<param name="saveDir">保存的本地⽂件夹路径</param>public void DownFtpDir(string ftpDir, string saveDir){List<FileStruct> files = ListFilesAndDirectories(ftpDir);if (!Directory.Exists(saveDir)){Directory.CreateDirectory(saveDir);}foreach (FileStruct f in files){if (f.IsDirectory) //⽂件夹,递归查询{DownFtpDir(ftpDir + "/" + , saveDir + "\\" + ); }else//⽂件,直接下载{DownLoadFile(ftpDir + "/" + , saveDir + "\\" + ); }}}#endregion}#region⽂件信息结构public struct FileStruct{public string Flags;public string Owner;public string Group;public bool IsDirectory;public DateTime CreateTime;public string Name;}public enum FileListStyle{UnixStyle,WindowsStyle,Unknown}#endregion。
Android使⽤ftp⽅式实现⽂件上传和下载功能近期在⼯作上⼀直再维护平台OTA在线升级项⽬,其中关于这个升级⽂件主要是存放于ftp服务器上的,然后客户端通过⾛ftp 协议⽅式下载⾄本地Android机进⾏⼀个系统升级操作。
那么今天将对ftp实现⽂件上传和下载进⾏⼀个使⽤总结,关于ftp这⽅⾯的理论知识如果不是太了解的各位道友,那么请移步作个具体的了解或者查阅相关资料。
那么先看看个⼈⼯作项⽬这个OTA升级效果图吧。
如下:下⾯是具体的接⼝实现:那么相关ftp的操作,已经被封装到ota.ftp这个包下,各位童鞋可以下载⽰例代码慢慢研究。
另外这个要是⽤ftp服务我们cline端需要再项⽬⼯程导⼊ftp4j-1.7.2.jar包这边作个使⽤的逻辑分析:⾸先在我们的项⽬⼯程FtpApplication中启动这个OtaService,其中OtaService作为⼀个服务运⾏起来,在这个服务⾥⾯拿到封装好ftp相关接⼝的DownLoad.java进⾏ftp⽂件操作,关键代码如下:public void startDownload() {// TODO Auto-generated method stubmDownLoad.start();}public void stopDownload() {mDownLoad.stop();}public void cancel() {mDownLoad.cancel();}public String getOldDate() {return mDownLoad.getDatabaseOldDate();}public String getOldVersion() {return mDownLoad.getDatabaseOldVersion();}public void checkVer(String serverRoot) {// TODO Auto-generated method stubmDownLoad = DownLoad.getInstance();mDownLoad.setServeRoot(serverRoot);mDownLoad.setFtpInfo(mApp.mFtpInfo);mDownLoad.checkUpgrade();}FTPToolkit.javapackage com.asir.ota.ftp;import it.sauronsoftware.ftp4j.FTPClient;import it.sauronsoftware.ftp4j.FTPFile;import java.io.File;import java.util.List;import com.asir.ota.clinet.PathToolkit;import com.asir.ota.ftp.DownLoad.MyFtpListener;/*** FTP客户端⼯具**/public final class FTPToolkit {private FTPToolkit() {}/*** 创建FTP连接** @param host* 主机名或IP* @param port* ftp端⼝* @param username* ftp⽤户名* @param password* ftp密码* @return ⼀个客户端* @throws Exception*/public static FTPClient makeFtpConnection(String host, int port,String username, String password) throws Exception {FTPClient client = new FTPClient();try {client.connect(host, port);if(username != null && password != null) {client.login(username, password);}} catch (Exception e) {throw new Exception(e);}return client;}/*** FTP下载⽂件到本地⼀个⽂件夹,如果本地⽂件夹不存在,则创建必要的⽬录结构 ** @param client* FTP客户端* @param remoteFileName* FTP⽂件* @param localPath* 存的本地⽂件路径或⽬录* @throws Exception*/public static void download(FTPClient client, String remoteFileName,String localPath, long startPoint, MyFtpListener listener) throws Exception {String localfilepath = localPath;int x = isExist(client, remoteFileName);File localFile = new File(localPath);if (localFile.isDirectory()) {if (!localFile.exists())localFile.mkdirs();localfilepath = PathToolkit.formatPath4File(localPath+ File.separator + new File(remoteFileName).getName());}if (x == FTPFile.TYPE_FILE) {try {if (listener != null)client.download(remoteFileName, new File(localfilepath),startPoint, listener);elseclient.download(remoteFileName, new File(localfilepath), startPoint);} catch (Exception e) {throw new Exception(e);}} else {throw new Exception("the target " + remoteFileName + "not exist");}}/*** FTP上传本地⽂件到FTP的⼀个⽬录下** @param client* FTP客户端* @param localfile* 本地⽂件* @param remoteFolderPath* FTP上传⽬录* @throws Exception*/public static void upload(FTPClient client, File localfile,String remoteFolderPath, MyFtpListener listener) throws Exception {remoteFolderPath = PathToolkit.formatPath4FTP(remoteFolderPath);try {client.changeDirectory(remoteFolderPath);if (!localfile.exists())throw new Exception("the upload FTP file"+ localfile.getPath() + "not exist!");if (!localfile.isFile())throw new Exception("the upload FTP file"+ localfile.getPath() + "is a folder!");if (listener != null)client.upload(localfile, listener);elseclient.upload(localfile);client.changeDirectory("/");} catch (Exception e) {throw new Exception(e);}}/*** FTP上传本地⽂件到FTP的⼀个⽬录下** @param client* FTP客户端* @param localfilepath* 本地⽂件路径* @param remoteFolderPath* FTP上传⽬录* @throws Exception*/public static void upload(FTPClient client, String localfilepath,String remoteFolderPath, MyFtpListener listener) throws Exception {File localfile = new File(localfilepath);upload(client, localfile, remoteFolderPath, listener);}/*** 批量上传本地⽂件到FTP指定⽬录上** @param client* FTP客户端* @param localFilePaths* 本地⽂件路径列表* @param remoteFolderPath* FTP上传⽬录* @throws Exception*/public static void uploadListPath(FTPClient client,List<String> localFilePaths, String remoteFolderPath, MyFtpListener listener) throws Exception { remoteFolderPath = PathToolkit.formatPath4FTP(remoteFolderPath);try {client.changeDirectory(remoteFolderPath);for (String path : localFilePaths) {File file = new File(path);if (!file.exists())throw new Exception("the upload FTP file" + path + "not exist!");if (!file.isFile())throw new Exception("the upload FTP file" + path+ "is a folder!");if (listener != null)client.upload(file, listener);elseclient.upload(file);}client.changeDirectory("/");} catch (Exception e) {throw new Exception(e);}}/*** 批量上传本地⽂件到FTP指定⽬录上** @param client* FTP客户端* @param localFiles* 本地⽂件列表* @param remoteFolderPath* FTP上传⽬录* @throws Exception*/public static void uploadListFile(FTPClient client, List<File> localFiles,String remoteFolderPath, MyFtpListener listener) throws Exception {try {client.changeDirectory(remoteFolderPath);remoteFolderPath = PathToolkit.formatPath4FTP(remoteFolderPath);for (File file : localFiles) {if (!file.exists())throw new Exception("the upload FTP file" + file.getPath()+ "not exist!");if (!file.isFile())throw new Exception("the upload FTP file" + file.getPath()+ "is a folder!");if (listener != null)client.upload(file, listener);elseclient.upload(file);}client.changeDirectory("/");} catch (Exception e) {throw new Exception(e);}}/*** 判断⼀个FTP路径是否存在,如果存在返回类型(FTPFile.TYPE_DIRECTORY=1、FTPFile.TYPE_FILE=0、 * FTPFile.TYPE_LINK=2) 如果⽂件不存在,则返回⼀个-1** @param client* FTP客户端* @param remotePath* FTP⽂件或⽂件夹路径* @return 存在时候返回类型值(⽂件0,⽂件夹1,连接2),不存在则返回-1*/public static int isExist(FTPClient client, String remotePath) {remotePath = PathToolkit.formatPath4FTP(remotePath);FTPFile[] list = null;try {list = client.list(remotePath);} catch (Exception e) {return -1;}if (list.length > 1)return FTPFile.TYPE_DIRECTORY;else if (list.length == 1) {FTPFile f = list[0];if (f.getType() == FTPFile.TYPE_DIRECTORY)return FTPFile.TYPE_DIRECTORY;// 假设推理判断String _path = remotePath + "/" + f.getName();try {int y = client.list(_path).length;if (y == 1)return FTPFile.TYPE_DIRECTORY;elsereturn FTPFile.TYPE_FILE;} catch (Exception e) {return FTPFile.TYPE_FILE;}} else {try {client.changeDirectory(remotePath);return FTPFile.TYPE_DIRECTORY;} catch (Exception e) {return -1;}}}public static long getFileLength(FTPClient client, String remotePath) throws Exception {String remoteFormatPath = PathToolkit.formatPath4FTP(remotePath);if(isExist(client, remotePath) == 0) {FTPFile[] files = client.list(remoteFormatPath);return files[0].getSize();}else {throw new Exception("get remote file length error!");}}/*** 关闭FTP连接,关闭时候像服务器发送⼀条关闭命令** @param client* FTP客户端* @return 关闭成功,或者链接已断开,或者链接为null时候返回true,通过两次关闭都失败时候返回false*/public static boolean closeConnection(FTPClient client) {if (client == null)return true;if (client.isConnected()) {try {client.disconnect(true);return true;} catch (Exception e) {try {client.disconnect(false);} catch (Exception e1) {e1.printStackTrace();return false;}}}return true;}}包括登录,开始下载,取消下载,获取升级⽂件版本号和服务器版本校验等。
如何通过FTP下载文件一、什么是FTPFTP(File Transfer Protocol)即文件传输协议,是用于在计算机之间传输文件的标准协议。
通过FTP,我们可以方便地将文件从一个计算机上传到另一个计算机,或从服务器下载到本地计算机上。
二、准备工作在开始使用FTP下载文件之前,需要进行以下准备工作:1. 安装FTP客户端软件:常见的FTP软件包括FileZilla、CuteFTP、FlashFXP等。
可以根据个人需要选择合适的FTP客户端软件并安装在计算机上。
2. 获取FTP服务器信息:需要知道要从哪个FTP服务器下载文件,包括FTP服务器的地址(通常是一个IP地址或域名)、端口号、用户名和密码。
这些信息通常由FTP服务器的管理员提供。
三、使用FTP客户端下载文件的步骤1. 启动FTP客户端软件并打开连接窗口。
2. 在连接窗口中填写FTP服务器的地址、端口号、用户名和密码等信息,然后点击连接按钮。
3. 连接成功后,FTP客户端软件会显示远程服务器上的文件列表。
浏览文件列表,找到要下载的文件所在的目录。
4. 双击或右键单击要下载的文件,选择下载或保存选项。
5. 指定文件保存的路径和名称,然后点击确定按钮。
6. FTP客户端软件会开始下载文件,并显示下载进度。
下载完成后,可以在指定的路径中找到下载好的文件。
四、注意事项在通过FTP下载文件时,需要注意以下事项,以确保下载过程的顺利进行:1. 确保FTP服务器的地址、端口号、用户名和密码等信息输入正确,否则无法成功连接到FTP服务器。
2. 在下载大文件时,建议使用稳定的网络环境,并确保本地磁盘空间足够。
3. 如果下载过程中出现连接中断或下载失败等情况,可以尝试重新连接或使用其他FTP客户端软件进行下载。
4. 部分FTP服务器需要进行被动模式(PASV)设置,以允许客户端与服务器之间建立数据连接。
如果下载过程中遇到连接问题,可以尝试切换到被动模式。
五、总结通过FTP下载文件是一种常见且便利的方式,适用于从服务器下载文件到本地计算机的场景。