15158846557 在线咨询 在线咨询
15158846557 在线咨询
所在位置: 首页 > 营销资讯 > 网站运营 > 如何搭建Ftp服务器

如何搭建Ftp服务器

时间:2023-07-31 08:54:01 | 来源:网站运营

时间:2023-07-31 08:54:01 来源:网站运营

如何搭建Ftp服务器:

一、简介

最近搭建热更服务器,了解到可能需要搭一个Ftp服务器用来上传文件,于是乎了解了下相关内容,并成功搭建了一个本地Ftp服务器,所以写一篇笔记记录一下这个过程中踩过的坑!

二、关于搭建Ftp服务器的搭建

关于如何搭建Ftp服务器,网上其实有很多文章介绍,就不多说,直接贴出参考连接,笔者亲测没问题!

三、上传文件到Ftp Server实践

本文以c#举例,代码如下,供大家参考。其他语言都是类似的,大家可以自行扩展。

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net;using System.Text;namespace Module.HotPatching{ class FtpService { private NetworkCredential _credential; private string _rootUri; private bool _usePassive; private readonly List<string> _directories = new List<string>(); private readonly List<string> _files = new List<string>(); public FtpService(string userName, string password, string rootUri, bool usePassive) { if (string.IsNullOrEmpty(rootUri)) { throw new ArgumentException("rootUri"); } _credential = new NetworkCredential(userName, password); _rootUri = FixUrl(rootUri); _usePassive = usePassive; GetInfoRecursive(""); } #region utility static string FixUrl(string old) { return !string.IsNullOrEmpty(old) ? old.Replace("//", "/").TrimEnd('/') : ""; } static string FixRelativePath(string old) { return !string.IsNullOrEmpty(old) ? old.Replace("//", "/").TrimEnd('/').TrimStart('/') : ""; } #endregion #region API /// <summary> /// 将若干个文件传到 ftp 服务器 /// </summary> /// <param name="files">上传的文件的路径</param> /// <param name="ftpFolders">上传到ftpserver的目标文件夹的相对文件夹</param> /// <param name="ftpFolder">上传ftpserver的目标文件夹</param> public void Upload(string[] files, string[] ftpFolders,string ftpFolder) { if (files == null || ftpFolders == null) throw new ArgumentNullException("files == null || ftpFolders == null"); if (files.Length != ftpFolders.Length) throw new ArgumentException("files.Length != ftpFolders.Length"); if (files.Length <1) return; ftpFolder = FixRelativePath(ftpFolder); // 先创建好文件夹 List<string> targetFolders = new List<string>(); foreach (var folder in ftpFolders) { string fixedPath = FixRelativePath(folder); if (ftpFolder == fixedPath) { continue; } string[] words = fixedPath.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < words.Length; i++) { string path = string.Empty; for (int j = 0; j <= i; j++) path = string.Format("{0}/{1}", path, words[j]); if (!targetFolders.Contains(path)) targetFolders.Add(path); } } foreach (var f in targetFolders) { CreateFolder(f); } // 上传 for (int i = 0; i < files.Length; i++) UploadFile(files[i], ftpFolders[i]); Console.WriteLine("All files are uploaded succeed!"); } public void UploadFile(string absolutePath, string relativeFolder) { string name = Path.GetFileName(absolutePath); string uri = CombineUri(relativeFolder, name); byte[] srcFileBuffer = File.ReadAllBytes(absolutePath); FtpWebRequest request = CreateRequest(uri, WebRequestMethods.Ftp.UploadFile); request.ContentLength = srcFileBuffer.Length; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(srcFileBuffer,0, srcFileBuffer.Length); _files.Add(string.Format("{0}/{1}", FixRelativePath(relativeFolder), name)); Console.WriteLine("Upload file succeed! {0} -> {1}", absolutePath, uri); } /// <summary> /// 将整个文件夹的内容传到ftp服务器,目录结构保持不变 /// </summary> /// <param name="folder"></param> /// <param name="ftpFolder"></param> /// <exception cref="ArgumentException"></exception> public void Upload(string folder, string ftpFolder) { if (string.IsNullOrEmpty(folder)) throw new ArgumentException("folder"); folder = FixUrl(folder); ftpFolder = FixRelativePath(ftpFolder); string[] files = Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories); string[] folders = new string[files.Length]; for (int i = 0; i < files.Length; i++) { string fileDir = FixUrl(Path.GetDirectoryName(files[i])); string relativeFolder = FixRelativePath(fileDir.Replace(folder, "")); folders[i] = string.Format("{0}/{1}", ftpFolder, relativeFolder); } // 上传 Upload(files, folders,ftpFolder); } /// <summary> /// 上传字符串到ftp server /// </summary> /// <param name="src"></param> /// <param name="relativePath">Ftp上的目标文件相对路径</param> /// <exception cref="ArgumentException"></exception> public void UploadString(string src, string relativePath) { if (string.IsNullOrEmpty(src)) throw new ArgumentException("src"); string uri = CombineUri(relativePath); byte[] buffer = Encoding.Default.GetBytes(src); FtpWebRequest request = CreateRequest(uri, WebRequestMethods.Ftp.UploadFile); request.ContentLength = buffer.Length; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buffer,0, buffer.Length); _files.Add(FixRelativePath(relativePath)); } public string DownloadFile(string relativePath) { relativePath = FixRelativePath(relativePath); if (string.IsNullOrEmpty(relativePath)) return null; string fullUri = CombineUri(relativePath); FtpWebRequest request = CreateRequest(fullUri, WebRequestMethods.Ftp.DownloadFile); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader sr = new StreamReader(stream); string text = sr.ReadToEnd(); response.Dispose(); stream.Dispose(); sr.Dispose(); return text; } #endregion #region private private FtpWebRequest CreateRequest(string uri, string method) { FtpWebRequest request = (FtpWebRequest) WebRequest.Create(uri); request.Method = method; request.Credentials = _credential; request.UsePassive = _usePassive; request.UseBinary = true; request.KeepAlive = true; return request; } private void GetInfoRecursive(string relativePath) { string fullUri = CombineUri(relativePath); FtpWebRequest request = CreateRequest(fullUri, WebRequestMethods.Ftp.ListDirectoryDetails); FtpWebResponse response = (FtpWebResponse) request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); List<string> dirs = new List<string>(); while (!reader.EndOfStream) { string line = reader.ReadLine(); string[] words = line.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries); string name = words.Last(); if (name != "." && name != "..") { char type = line[0]; string newPath = !string.IsNullOrEmpty(relativePath) ? string.Format("{0}/{1}", relativePath, name) : name; newPath = FixRelativePath(newPath); if (type == 'd') { _directories.Add(newPath); dirs.Add(newPath); } else if (type == '-') { _files.Add(newPath); } } } response.Dispose(); stream.Dispose(); reader.Dispose(); foreach (var dir in dirs) { GetInfoRecursive(dir); } } private string CombineUri(params string[] relativePaths) { string uri = _rootUri; foreach (var p in relativePaths) { if (!string.IsNullOrEmpty(p)) uri = string.Format("{0}/{1}", uri, FixRelativePath(p)); } return uri; } private void CreateFolder(string relativePath) { relativePath = FixRelativePath(relativePath); if (string.IsNullOrEmpty(relativePath)) throw new ArgumentException("relativePath"); if (_directories.Contains(relativePath)) return; string fullUri = CombineUri(relativePath); try { FtpWebRequest request = CreateRequest(fullUri, WebRequestMethods.Ftp.MakeDirectory); WebResponse response = request.GetResponse(); response.Dispose(); _directories.Add(relativePath); } catch (Exception e) { // ignored 如果目录已存在,会报异常,可以忽略 } Console.WriteLine("Create folder succeed! {0}", fullUri); } #endregion }}

四、关于过程中遇到的些小问题

4.1 关于Ftp账号名

上传文件ftpserver时,需要输入用户名及密码,如果是匿名的话,可以在username处写anonymous,密码随意

4.2 上传文件成功后,Ftp服务器对应位置无文件

ftp server有时响应会慢一些,此时,可以打开具体的物理文件夹查看,如果上传成功,对应物理文件夹一定会有,而通过ftp server查看可能要稍等一下才会显示,也可以点击下文件夹的刷新,试试看。

五、结语

关于Ftp服务器的搭建,还是蛮轻松的,主要网上已经有大量文章讲述,笔者这里只是做个简单记录,哈哈~

关键词:服务

74
73
25
news

版权所有© 亿企邦 1997-2025 保留一切法律许可权利。

为了最佳展示效果,本站不支持IE9及以下版本的浏览器,建议您使用谷歌Chrome浏览器。 点击下载Chrome浏览器
关闭