第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下载文件是一种常见且便利的方式,适用于从服务器下载文件到本地计算机的场景。
sftp文件上传和下载下面是java 代码sftp文件上传和下载具体实现1.连接服务器类package Test;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import com.jcraft.jsch.Channel;import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.JSch;import com.jcraft.jsch.Session;/** @author lixiongjun** 利用JSch包实现创建ChannelSftp通信对象的工具类* 2015-1-27 上午10:03:21*/public class SftpUtil {private static String ip = null; // ip 主机IPprivate static int port = -1; // port 主机ssh2登陆端口,如果取默认值,传-1 private static String user = null; // user 主机登陆用户名private static String psw = null; // psw 主机登陆密码private static String servicePath = null; // 服务存储文件路径private static Properties prop = null;private static Session session = null;private static Channel channel = null;// 读取配置文件的参数static {prop = new Properties();ClassLoader cl = SftpUtil.class.getClassLoader(); InputStream is = cl.getResourceAsStream("Test/Sftp_UpDownload.properties"); try {prop.load(is);} catch (IOException e) {// System.out.println("读取配置文件出错!");e.printStackTrace();}ip = prop.getProperty("ip");port = Integer.parseInt(prop.getProperty("port"));user = prop.getProperty("user");psw = prop.getProperty("psw");servicePath = prop.getProperty("servicePath");}/*** 获取sftp通信** @return 获取到的ChannelSftp* @throws Exception*/public static ChannelSftp getSftp() throws Exception {ChannelSftp sftp = null;JSch jsch = new JSch();if (port <= 0) {// 连接服务器,采用默认端口session = jsch.getSession(user, ip);} else {// 采用指定的端口连接服务器session = jsch.getSession(user, ip, port);}// 如果服务器连接不上,则抛出异常if (session == null) {throw new Exception("session is null");}// 设置登陆主机的密码session.setPassword(psw);// 设置密码// 设置第一次登陆的时候提示,可选值:(ask | yes | no) session.setConfig("StrictHostKeyChecking", "no");// 设置登陆超时时间session.connect(30000);try {// 创建sftp通信通道channel = (Channel) session.openChannel("sftp"); channel.connect();sftp = (ChannelSftp) channel;// 进入服务器指定的文件夹sftp.cd(servicePath);} catch (Exception e) {e.printStackTrace();}return sftp;}/*** 关闭连接*/public static void closeSftp() {if (channel != null) {if (channel.isConnected())channel.disconnect();}if (session != null) {if (session.isConnected())session.disconnect();}}}2.上传下载工具类package Test;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import org.junit.Test;import com.jcraft.jsch.ChannelSftp;public class SftpUploadOrDownload {/** @author lixiongjun** 实现sftp文件上传下载的工具类* 2015-1-27 下午15:13:26*//*** 上传本地文件到服务器* @param srcPath 本地文件路径* @param dstFilename 目标文件名* @return 是否上传成功*/public boolean upload(String srcPath,String dstFilename){ ChannelSftp sftp=null;try {sftp =SftpUtil.getSftp();sftp.put(srcPath,dstFilename);return true;} catch (Exception e) {e.printStackTrace();return false;}SftpUtil.closeSftp();}}/*** 上传本地文件到服务器* @param in 输入流* @param dstFilename 目标文件名* @return 是否上传成功*/public boolean uploadBystrem(InputStream in,String dstFilename){ ChannelSftp sftp=null;try {sftp =SftpUtil.getSftp();sftp.put(in,dstFilename);return true;} catch (Exception e) {e.printStackTrace();return false;}finally{SftpUtil.closeSftp();}}/*** 把服务器文件下载到本地* @param desPath 下载到本地的目标路径* @param srcFilename 源文件名* @return 是否下载成功*/public boolean download(String srcFilename,String dstPath){ ChannelSftp sftp=null;try {sftp =SftpUtil.getSftp();sftp.get(srcFilename,dstPath);return true;} catch (Exception e) {e.printStackTrace();return false;}SftpUtil.closeSftp();}}/*** 获取服务器文件的内容,只对文本文件有效* @param srcFilename 服务器所在源文件名* @return 文件内容*/public String getServiceFileContext(String srcFilename){ ChannelSftp sftp=null;InputStream in=null;BufferedReader br=null;String filecontext="";try {sftp =SftpUtil.getSftp();in=sftp.get(srcFilename);br=new BufferedReader(new InputStreamReader(in)); String str=br.readLine();while(str!=null){filecontext+=str+"\n";str=br.readLine();}} catch (Exception e) {e.printStackTrace();}finally{try {br.close();in.close();} catch (IOException e) {e.printStackTrace();}SftpUtil.closeSftp();}return filecontext;}/*** 删除服务器上文件* @param filename 要删除的文件名* @return 是否删除成功*/public boolean remove(String filename){ ChannelSftp sftp=null;try {sftp =SftpUtil.getSftp();sftp.rm(filename);return true;} catch (Exception e) {e.printStackTrace();return false;}finally{SftpUtil.closeSftp();}}@Testpublic void TestSftpUpload(){if(upload("E:/test.txt","test.txt")){System.out.println("上传文件成功");}else{System.out.println("上传文件失败");}}@Testpublic void TestSftpDownload(){if(download("test.txt","E:/downtest.txt")){ System.out.println("下载文件成功");}else{System.out.println("下载文件失败");}}@Testpublic void TestSftpgetServiceFileContext(){String context=getServiceFileContext("test.txt"); System.out.println(context);}@Testpublic void TestSftpRemove(){if(remove("test.txt")){System.out.println("删除文件成功");}else{System.out.println("删除文件失败");}}}配置文件 Sftp_UpDownload.propertiesip=127.0.0.1port=22user=testpsw=testservicePath=testpath下载的get方法详情API /rangqiwei/article/details/9002046上传的put方法详情 API /longyg/archive/2012/06/25/2556576.html。
使用FTP下载文件的流程1. 简介FTP(File Transfer Protocol)是一种用于在计算机之间传输文件的标准网络协议。
通过FTP,用户可以在不同的系统之间进行文件上传、下载和删除等操作。
在本文中,我们将讨论如何使用FTP下载文件的流程。
2. 准备工作在使用FTP下载文件之前,我们需要进行一些准备工作。
2.1 确定FTP服务器地址和端口号首先,我们需要确定要从哪个FTP服务器下载文件。
通常,FTP服务器的地址是一个IP地址或域名,而端口号一般是21。
获取到FTP服务器的地址和端口号后,我们可以开始配置FTP客户端。
2.2 配置FTP客户端在使用FTP客户端之前,我们需要下载和安装一个FTP客户端软件。
常见的FTP客户端软件包括FileZilla、WinSCP等。
下载安装完毕后,我们需要进行一些配置。
1.打开FTP客户端软件。
2.在配置界面中,输入FTP服务器的地址和端口号。
3.输入登录凭证,包括用户名和密码。
3. 下载文件的流程下面是使用FTP下载文件的详细步骤:3.1 连接FTP服务器1.打开FTP客户端软件。
2.在主界面中,点击连接按钮或输入命令来连接FTP服务器。
3.2 浏览远程目录1.成功连接到FTP服务器后,你将看到远程目录的列表。
2.导航至所需的目录,使用cd命令或点击相应目录进行导航。
3.3 下载文件1.在远程目录中找到要下载的文件。
2.右键单击文件或选择文件并点击下载按钮。
3.指定将文件下载到本地计算机的位置。
4.点击下载按钮开始下载。
3.4 等待下载完成1.下载过程会花费一些时间,取决于文件的大小和您的网络速度。
2.在下载完成之前,请不要关闭FTP客户端或断开与FTP服务器的连接。
3.5 验证文件完整性1.下载完成后,可以使用文件管理器或计算机终端来验证文件的完整性。
2.比较本地文件的哈希值或文件大小与FTP服务器上的文件是否一致。
4. 注意事项在使用FTP下载文件时,有一些注意事项需要我们注意:•确保FTP服务器的地址和端口号是正确的。
Java8实现FTP及SFTP⽂件上传下载有⽹上的代码,也有⾃⼰的理解,代码备份 ⼀般连接windows服务器使⽤FTP,连接linux服务器使⽤SFTP。
linux都是通过SFTP上传⽂件,不需要额外安装,⾮要使⽤FTP的话,还得安装FTP服务(虽然刚开始我就是这么⼲的)。
另外就是jdk1.8和jdk1.7之前的⽅法有些不同,⽹上有很多jdk1.7之前的介绍,本篇是jdk1.8的添加依赖Jsch-0.1.54.jar<!-- https:///artifact/com.jcraft/jsch --><dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.54</version></dependency>FTP上传下载⽂件例⼦import .ftp.FtpClient;import .ftp.FtpProtocolException;import java.io.*;import .InetSocketAddress;import .SocketAddress;/*** Java⾃带的API对FTP的操作*/public class Test {private FtpClient ftpClient;Test(){/*使⽤默认的端⼝号、⽤户名、密码以及根⽬录连接FTP服务器*/this.connectServer("192.168.56.130", 21, "jiashubing", "123456", "/home/jiashubing/ftp/anonymous/");}public void connectServer(String ip, int port, String user, String password, String path) {try {/* ******连接服务器的两种⽅法*******/ftpClient = FtpClient.create();try {SocketAddress addr = new InetSocketAddress(ip, port);ftpClient.connect(addr);ftpClient.login(user, password.toCharArray());System.out.println("login success!");if (path.length() != 0) {//把远程系统上的⽬录切换到参数path所指定的⽬录ftpClient.changeDirectory(path);}} catch (FtpProtocolException e) {e.printStackTrace();}} catch (IOException ex) {ex.printStackTrace();throw new RuntimeException(ex);}}/*** 关闭连接*/public void closeConnect() {try {ftpClient.close();System.out.println("disconnect success");} catch (IOException ex) {System.out.println("not disconnect");ex.printStackTrace();throw new RuntimeException(ex);}}/*** 上传⽂件* @param localFile 本地⽂件* @param remoteFile 远程⽂件*/public void upload(String localFile, String remoteFile) {File file_in = new File(localFile);try(OutputStream os = ftpClient.putFileStream(remoteFile);FileInputStream is = new FileInputStream(file_in)) {byte[] bytes = new byte[1024];int c;while ((c = is.read(bytes)) != -1) {os.write(bytes, 0, c);}System.out.println("upload success");} catch (IOException ex) {System.out.println("not upload");ex.printStackTrace();} catch (FtpProtocolException e) {e.printStackTrace();}}/*** 下载⽂件。
实验四文件的上传和下载6.1.3 FTP的访问形式用户对FTP服务的访问有两种形式:匿名FTP和用户FTP。
1.匿名FTP在Internet上用户使用FTP进行文件下载操作的优点是用户可以以“匿名”方式登录远程的FTP服务器。
匿名FTP允许远程用户访问FTP服务器,前提是可以同服务器建立物理连接。
无论用户是否拥有该FTP服务器的账号,都可以使用“anonymous”用户名进行登录,一般以E-mail地址做口令。
匿名FTP服务对用户的使用有一定的限制,通常只允许用户获取文件,而不允许用户修改现有的文件或向FTP服务器传送文件,并对用户获取文件的范围也有一定的限制。
这种FTP服务比较安全,能支持大多数文件类型。
2.用户FTP用户FTP方式为已在服务器建立了特定账号的用户使用,必须以用户名和口令来登录,这种FTP应用存在一定的安全风险。
当用户从Internet或Intranet与FTP服务连接时,所使用的口令是以明文方式传输的,接触系统的任何人都可以使用相应的程序来获取该用户的账号和口令,然后盗用这些信息在系统上登录,从而对系统产生威胁。
当然,对不同的用户,FTP 往往限制某些功能,防止用户对系统进行全面的访问或完全控制。
一些通过FTP开展的商业服务,赋予用户的账号和口令都是在短期内有效的临时账号。
另外,使用FTP还需要注意“端口”号。
端口是服务器使用的一个通道,它可以让具有同样地址的服务器同时提供多种不同的功能。
例如,一个地址为211.85.193.152的服务器,可以同时作为WWW服务器和FTP服务器,WWW服务器使用端口是80,而FTP服务器使用端口21。
6.1.4 FTP的常用命令FTP服务需要FTP客户来访问。
早期的FTP客户软件是以字符为基础的,与使用DOS 命令行列出文件和复制文件相似,以字符为基础的程序用于登录到远程计算机,浏览目录及传送文件。
当然更多的是专门的FTP客户软件,基于图形用户界面的客户软件,如CuteFTP,使用更加方便,功能也更强大。
《计算机网络课程设计》论文2012 —2013学年第二学期题目: FTP程序设计专业班级:软件工程.NET10—2姓名:刘天鹏王硕崔毅学号:311009070220311009070225311009070212指导老师:王磊日期:2013-7—4目录系统开发背景。
.。
..。
.。
...。
.。
.。
....。
.....。
...。
..。
.。
.。
.。
.3系统研究意义。
......。
.。
.。
..。
.....。
.。
..。
...。
.。
.。
...。
.。
. (3)1。
相关技术..。
...。
.。
.。
..。
.....。
......。
.。
....。
.41。
1 NET简介.。
...。
..。
..。
.。
..。
..。
........。
.。
..。
..。
.。
..。
....。
41。
2 Visual Studio 。
NET简介..。
......。
.。
..。
.。
.。
.。
..。
.1.3 C#简介。
.。
..。
..。
....。
.。
.......。
..。
.。
.。
41.4 Winsock简介。
..。
.....。
...。
.。
.。
...。
.。
..。
..。
...。
...。
..。
4 1。
5 FTP简介...。
.。
.。
...。
.。
.。
.。
...。
.。
...。
.。
.。
.。
.。
.51。
5.1工作原理。
..。
.。
.....。
.。
.。
...。
.。
.。
...。
....。
.。
51.5.2工作模式...。
.。
.。
..。
.。
....。
....。
.。
..。
..。
.。
.61.5.3传输模式。
.。
..。
.。
.。
...。
..。
..。
..。
...。
...。
.。
..。
72.功能模块的分析。
.。
.。
......。
.。
...。
..。
.。
..。
....。
..。
.。
..。
..。
82.1 系统总体功能分析。
.。
.。
.。
..。
..。
.。
.。
..。
..。
.。
.。
.。
.。
.。
.92。
2 启动服务器.。
.。
....。
.。
.。
...。
.。
.。
.。
..。
...。
.。
..。
...。
9 2。
3链接模块功能分析。
、下载和安装1、下载。
2、安装。
展开压缩文件“ServU3b7.zip”,执行其中的“setup.exe”,即可开始安装;全部选默认选项即可。
安装完成后不需重新启动,直接在“开始→程序→Serv-UFTPServer”中就能看到相关文件。
如下图:二、建立第一个可用的FTP服务器1、比如本机IP地址为“192.168.0.48”,已建立好域名“”的相关DNS记录。
2、打开Serv-U管理器。
选上图的“Serv-UAdministrator”,即出现“SetupWizard”(设置向导)。
此向导可以帮你轻松地完成基本设置,因此建议使用它。
直接选“Next”(下一步)。
如下图:3、请随着安装向导按以下步骤来进行操作:⑴IPaddress(IP地址):输入“192.168.0.48”。
(如果使用动态的IP地址,或无合法的IP地址则此项应保持为空。
)⑵Domainname(域名):输入“”。
⑶Installassystemserver(安装成一个系统服务器吗):选“Yes”。
⑷Allowanonymousaccess(接受匿名登录吗):此处可根据自己需要选择;比如选“Yes”。
⑸anonymoushomedirectory(匿名主目录):此处可输入(或选择)一个供匿名用户登录的主目录。
⑹Lockanonymoususersintotheirhomedirectory(将用户锁定在刚才选定的主目录中吗):即是否将上步的主目录设为用户的根目录;一般选“Yes”。
⑺Createnamedaccount(建立其他帐号吗):此处询问是否建立普通登录用户帐号;一般选“Yes”。
⑻Accountloginname(用户登录名):普通用户帐号名,比如输入“nanshan”。
⑼Password(密码):设定用户密码。
由于此处是用明文(而不是*)显示所输入的密码,因此只输一次。
⑽Homedirectory(主目录):输入(或选择)此用户的主目录。
第7章 传 输 文 件教学提示:文件上传、下载,FTP文件传输协议概念是理解文件传输的基本内容。
熟悉常用的文件传输软件——网际快车FlashGet(JetCar)及CuteFTP的安装、设置和使用是掌握文件传输的主要内容。
教学要求:文件上传、下载的基本概念。
掌握FTP文件传输协议的含义及设置。
掌握常用的文件传输软件——网际快车FlashGet(JetCar)及CuteFTP的安装、设置和使用。
掌握文件的压缩、解压缩的概念及WinRAR压缩文件管理软件的使用方法。
7.1 使用Internet Explorer上传和下载文件网络的最大一个功能就是资源共享,所以在网络上经常要用到文件的传输。
文件的传输也就是指上传和下载。
7.1.1 上传文件文件上传即是将本地文件送上服务器。
在IE中可以使用拖曳的方法,把文件直接拖到服务器所在的窗体。
注意:在匿名登录的情况下,并不是所有的FTP站点都允许上传文件,一般在Incoming 目录可能提供匿名上传的权限。
如果站点是UNIX的服务器,也可以直接改变文件的属性,方法是选中需要改变文件属性的文件(目录)后按鼠标右键,在弹出的快捷菜单中选择Change file attributes命令,然后在新窗口中根据需要改变文件的属性即可。
7.1.2 下载文件文件的下载即是将远程站点上的文件下载到本地。
只要双击站点文件显示区显示的文件名,然后选择保存的文件夹就可以将站点上的本文件下载到本地。
7.2 使用Internet Explorer访问FTP服务器7.2.1 FTP的基本概念FTP是英文File Transfer Protocol (文件传输协议)的缩写。
FTP是在使用Internet技术的网络上,在两台计算机之间交换文件的基本方法,FTP是TCP/IP协议族中位于应用层的协议,它是一个高层协议,在传输层它使用面向连接的、可靠的TCP协议,因此FTP的传输是可靠的。
简言之,FTP就是完成两台计算机之间的复制,从远程计算机复制文件至自第7章 传输文件 ·157··157·己的计算机上,称之为“下载”(download)文件。
敲好最近有机会用到ftp发送接收文件,总结一下oracle里面ftp发送接收的方法。
Java 中可以使用.ftp.FtpClient实现简单的ftp操作,这是在oracle数据库中有提供api 的。
我个人觉得对于ftp的操作用java方式比较方便,代码简单容易懂而且广泛。
不过oracle 中也有提供ftp访问的包UTL_TCP,通过这个包也可以很方便的实现ftp操作。
Java方式实现ftp客户端操作在oracle数据库中有提供.ftp.FtpClient,所以可以直接使用该包完成简单的ftp操作在oracle数据库端。
这里有个问题没有解决:ftp文件追加时候,发现没有提供FtpClient.append()函数,但是在一般的java程序中式可以使用,测试都是在jdk1.4版本上进行的。
还是在oracle 里面这个功能不允许还是我没有找到append替代方法呢?createorreplaceandcompilejavasourcenamed remoteFtpClient ASpackage oracle.apps.zz.zzmes;importjava.io.BufferedReader;importjava.io.DataInputStream;importjava.io.File;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.RandomAccessFile;importjava.io.FileInputStream;importjava.util.StringTokenizer;.TelnetInputStream;.TelnetOutputStream;.ftp.FtpClient;.*;.ftp.*;//importorg.apache.*;//.ftp.*;//.ftp.FTP.*;//.ftp.FTP.*;publicclass remoteFtpClient{privateString host;privateString username;privateStringpassword;private FtpClientclient;public remoteFtpClient(){}public remoteFtpClient(String Host,String userName,StringpassWord){ this.host=Host;//ip地址ername=userName;;//用户名this.password=passWord;//密码this.client=new FtpClient();}public voidsetHost(String Host){host=Host;}public voidsetUserName(String userName){username=userName;}public voidsetPassword(String pwd){password=pwd;}/***********************************获取和远程ftp服务器的连接**********************************/ publicboolean getFtpConnection(){//client=new FtpClient();try{client.openServer(host);client.login(username,password);//client.ascii();client.binary();//client.setConnectTimeout(6000);//设置超时System.out.println("loginsucess");}catch(IOExceptione){//TODO Auto-generated catch blocke.printStackTrace();returnfalse;}returntrue;}/***********************************关闭ftp连接**********************************/public voidcloseConnection(){if(client!=null){try{client.closeServer();}catch(IOExceptione){//TODO Auto-generated catch blocke.printStackTrace();}client=null;}}/**************************************实现ftp文件上传*parameters*fileName:文件名*sendcontent:要发送的内容*path:上传的路径,路径为空则取登录ftp后的默认路径*return:成功返回true,失败返回false*************************************/publicboolean sendXml2Ftp(String fileName,String sendContent,String path){ try{if(path!=null)client.cd(path);//发现在数据库中不能使用client.append(path);String lineSeparator=System.getProperty("line.separator"); TelnetOutputStreamos=client.put(fileName);//创建一个新的文件或者覆盖//client.rename("index","wip");//重新命名文件名称//TelnetOutputStreamos=client.append(fileName);//os.write(sendContent.getBytes("UTF-8"));//os.write(sendContent.getBytes("GB2312"));String encoding=System.getProperty("file.encoding");os.write(sendContent.getBytes(encoding));os.close();//client.rename(arg0,arg1)//client.sendServer("DELEwip.xml");//删除文件}catch(IOExceptione){System.out.println("insertarecordtoerrortable!");//TODO Auto-generated catch blocke.printStackTrace();returnfalse;}returntrue;}publicstaticString replaceAllString(String str,String pattern,String replaces) {StringBuffer result=new StringBuffer();StringTokenizerstrToken=new StringTokenizer(str,pattern);while(strToken.hasMoreTokens()){result.append((String)strToken.nextToken());result.append(replaces);}return result.toString();}/***********************************实现ftp下载*parameters:*fileName:文件名称*path:文件路径*return:ftp文件内容**********************************/publicString loadXml2Temp(String fileName,String path){TelnetInputStreamfget;String xmlString=null;String encoding=System.getProperty("file.encoding");String temp;try{if(path!=null)client.cd(path);fget=client.get(fileName);//InputStreamReaders=new InputStreamReader(fget,"GB2312");//接收的字符集需要和要下载的文件最好字符集相同,否则在中文时候会有乱码InputStreamReaders=new InputStreamReader(fget,"UTF-8");BufferedReader in=new BufferedReader(s);StringBuffersb=new StringBuffer();while((temp=in.readLine())!=null){sb.append(temp.trim());sb.append("\n");}xmlString=sb.toString();s.close();}catch(IOExceptione){//TODO Auto-generated catch blocke.printStackTrace();returnnull;}return xmlString;}}通过在另一个java存储过程调用以上的以上ftp存储过程,可以实现ftp文件的上传下载例如:createorreplaceandcompilejavasourcenamed ftpSendGetTest ASpackage oracle.apps.zz.zzmes;importjava.sql.Clob;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.Hashtable;importoracle.xml.sql.query.OracleXMLQuery;importjava.io.*;.ftp.FtpClient;importoracle.sql.*;importoracle.jdbc.OracleDriver;importjava.sql.Connection;publicclass ftpSendGetTest{//实现ftp下载,并转换为xml文件格式并返回clobpublicstaticCLOB getXml(String host,String username,String pwd,String fileName,String path){String xml="";CLOB tempClob=null;//ftp类构造remoteFtpClientfc=new remoteFtpClient(host,username,pwd);if(fc.getFtpConnection()){//连接ftpxml=fc.loadXml2Temp(fileName,path);//调用下载函数if(xml!=null){try{//实现String转换为clobConnectionconn=new OracleDriver().defaultConnection();tempClob=CLOB.createTemporary(conn,true,CLOB.DURATION_SESSION); tempClob.open(CLOB.MODE_READWRITE);WritertempClobWriter=tempClob.getCharacterOutputStream(); tempClobWriter.write(xml);tempClobWriter.flush();tempClobWriter.close();tempClob.close();conn.close();}catch(SQLExceptione){//TODO Auto-generated catch blocke.printStackTrace();}catch(IOExceptione){//TODO Auto-generated catch blocke.printStackTrace();}}fc.closeConnection();//关闭ftp连接}return tempClob;}//发送数据到ftppublicstaticString sendxml(String host,String username,String pwd,String fileName,Str ing path,String content){String b="N";remoteFtpClientfc=new remoteFtpClient(host,username,pwd);if(fc.getFtpConnection())//连接ftp{if(fc.sendXml2Ftp(fileName,content,path))//发送文件b="Y";fc.closeConnection();//关闭ftp连接}return b;}Pl/sql中实现ftp客户端操作在oracle中提供了数据库包SYS.utl_tcp实现客户端操作。
FTP服务–⽤来传输⽂件的协议(FTP详解,附带超详细实验步骤)⼀、FTP协议概念1、FTP服务器默认使⽤TCP协议的20、21端⼝与客户端进⾏通信• 20端⼝⽤于建⽴数据连接,并传输⽂件数据• 21端⼝⽤于建⽴控制连接,并传输FTP控制命令2、FTP数据连接分为主动模式和被动模式• 主动模式: 服务器主动发起数据连接• 被动模式: 服务器被动等待数据连接⼆、FTP配置格式1、安装FTPyum install -y vsftpdcd /etc/vsftpd/cp vsftpd.conf vsftpd.conf.bak2、设置匿名⽤户访问的FTP服务(最⼤权限):修改配置⽂件vim /etc/vsftpd/vs ftpd.conf #修改配置⽂件anonymous_enable=YES #开启匿名⽤户访问。
默认E开启write enable=YES #开放服务器的写权限(若要上传,必须开启)。
默认已开启anon umask=022 #设置匿名⽤户所上传数据的权限掩码(反掩码)anon_ upload_ enable=YES #允许匿名⽤户.上传⽂件。
默认E已注释,需取消注释anon_ mkdir_ write_ enable=YES #允许匿名⽤户创建(上传)⽬录。
默认已注释,需取消注释anon other write enable=YES #允许删除、重命名、覆盖等操作。
需添加chmod 777 / var/ ftp/pub/ #为匿名访问ftp的根⽬录下的pub⼦⽬录设置最⼤权限,以便匿名⽤户.上传数据3、开启服务,关闭防⽕墙和增强型安全功能systemctl start vsftpd #开启FTP服务systemctl stop firewalld #关闭防⽕墙setenforce 04、匿名访问测试在Windows系统打开开始菜单,输⼊cmd命令打开命令提⽰符 ftp 192.168.80.10 #建⽴ftp连接#匿名访问,⽤户名为ftp,密码为空,直接回车即可完成登录ftp> pwd #匿名访问ftp的根⽬录为Linux系统的/var/ftp/⽬录ftp> ls #查看当前⽬录ftp> cd pub #切换到pub⽬录ftp> get ⽂件名 #下载⽂件到当前windows本地⽬录ftp> put ⽂件名 #上传⽂件到ftp⽬录ftp> quit #退出5、设置本地⽤户验证访问ftp,并禁⽌切换到ftp以外的⽬录(默认登录的根⽬录为本地⽤户的家⽬录):vim /etc/vsftpd/vs ftpd. conf #修改配置⽂件local enable=Yes #启⽤本地⽤户anonymous_enable=NO #关闭匿名⽤户访问write enable=YES #开放服务器的写权限(若要_上传,必须开启)local_umask=077 #可设置仅宿主⽤户拥有被上传的⽂件的权限( 反掩码)chroot_local_user=YES #将访问禁锢在⽤户的宿主⽬录中allow_writeable_chroot=YES #允许被限制的⽤户主⽬录具有写权限systemctl restart vsftpd #重启服务ftp 192.168.80.10或者ftp://zhangsan@192.168.80.106、修改匿名⽤户、本地⽤户登录的默认根⽬录 anon root=/ var/ Www/ html #anon_ root 针对匿名⽤户local root=/ var/www/html #local_ root 针对系统⽤户7、⽤户列表设置,修改配置⽂件(⿊名单、⽩名单设置) 使⽤user_list ⽤户列表⽂件vim /etc/vsftpd/user_ list #修改配置⽂件zhangsan #在末尾添加zhangsan⽤户vim /etc/vsttpd/vsttpd.cont #修改配置⽂件userlist enable=YES #启⽤user_ list⽤户列表⽂件userlist deny=NO #设置⽩名单,仅允许user_ list⽤户列表⽂件的⽤户访问。