二、關(guān)于搭建Ftp服務(wù)器的" />

国产成人精品无码青草_亚洲国产美女精品久久久久∴_欧美人与鲁交大毛片免费_国产果冻豆传媒麻婆精东

15158846557 在線咨詢 在線咨詢
15158846557 在線咨詢
所在位置: 首頁 > 營銷資訊 > 網(wǎng)站運營 > 如何搭建Ftp服務(wù)器

如何搭建Ftp服務(wù)器

時間:2023-07-31 08:54:01 | 來源:網(wǎng)站運營

時間:2023-07-31 08:54:01 來源:網(wǎng)站運營

如何搭建Ftp服務(wù)器:

一、簡介

最近搭建熱更服務(wù)器,了解到可能需要搭一個Ftp服務(wù)器用來上傳文件,于是乎了解了下相關(guān)內(nèi)容,并成功搭建了一個本地Ftp服務(wù)器,所以寫一篇筆記記錄一下這個過程中踩過的坑!

二、關(guān)于搭建Ftp服務(wù)器的搭建

關(guān)于如何搭建Ftp服務(wù)器,網(wǎng)上其實有很多文章介紹,就不多說,直接貼出參考連接,筆者親測沒問題!

三、上傳文件到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 服務(wù)器 /// </summary> /// <param name="files">上傳的文件的路徑</param> /// <param name="ftpFolders">上傳到ftpserver的目標(biāo)文件夾的相對文件夾</param> /// <param name="ftpFolder">上傳ftpserver的目標(biāo)文件夾</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); // 先創(chuàng)建好文件夾 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> /// 將整個文件夾的內(nèi)容傳到ftp服務(wù)器,目錄結(jié)構(gòu)保持不變 /// </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上的目標(biāo)文件相對路徑</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 }}

四、關(guān)于過程中遇到的些小問題

4.1 關(guān)于Ftp賬號名

上傳文件ftpserver時,需要輸入用戶名及密碼,如果是匿名的話,可以在username處寫anonymous,密碼隨意

4.2 上傳文件成功后,F(xiàn)tp服務(wù)器對應(yīng)位置無文件

ftp server有時響應(yīng)會慢一些,此時,可以打開具體的物理文件夾查看,如果上傳成功,對應(yīng)物理文件夾一定會有,而通過ftp server查看可能要稍等一下才會顯示,也可以點擊下文件夾的刷新,試試看。

五、結(jié)語

關(guān)于Ftp服務(wù)器的搭建,還是蠻輕松的,主要網(wǎng)上已經(jīng)有大量文章講述,筆者這里只是做個簡單記錄,哈哈~

關(guān)鍵詞:服務(wù)

74
73
25
news

版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。

為了最佳展示效果,本站不支持IE9及以下版本的瀏覽器,建議您使用谷歌Chrome瀏覽器。 點擊下載Chrome瀏覽器
關(guān)閉