C#上传到FTP Server
上传到FTP Server Controller
[HttpPost] public ActionResult Upload(HttpPostedFileBase[] files) { //廠別,部門,單號,單據類型,文件名,保存文件名,Seq,上傳人員,上傳時間 Enabled //1.保存文件,2.保存文件信息到數據庫表EMS_MT_EvidFile mtEvidFileBLL FtpWeb ftp = new FtpWeb(); var fi = files; string mtNO = Request["MTNO"].ToString(); int deptID = Convert.ToInt32( Request["DeptID"]); string docType = "MT"; //獲取周 string strWeek = System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(DateTime.Now, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday).ToString(); string strProName = "EMS_MT_EVIDFILE"; string fileExtenName = string.Empty; string fileName=string.Empty; var filePath = "/EMS" + "/" + "UploadDoc" + "/" + strProName + "/" + PlantID + "/" + DateTime.Now.ToString("yyyy") + strWeek.PadLeft(2, '0') + "/"; #region 創建文件路徑 ftp.MakeDirByUrlPath(filePath); #endregion if (fi != null) { try { var virtualPath = string.Empty; //最大seq int maxSeq = mtEvidFileBLL.GetMaxSeqByMTNO(string.Format(" PlantID = '{0}' and MTNO = '{1}' and DocType = '{2}' " ,PlantID,mtNO,docType)); ListfileModeles = new List (); foreach (var file in fi) { maxSeq++; int seq = maxSeq; if (seq > 5) { throw new Exception(string.Format("上傳失敗,已上傳{0}個檔案,最多只能上傳5個檔案!",seq-1)); } fileExtenName = System.IO.Path.GetExtension(file.FileName); fileName = string.Format("{0}_{1}{2}",mtNO, seq , fileExtenName); virtualPath = filePath + fileName; Lib.Model.EMS.Spart.MTEvidFile mtFileModel = new Lib.Model.EMS.Spart.MTEvidFile() { MTEvidFileGUID = ResultHelper.NewGuid, DeptID = (int)deptID, DOCType = docType, EmpID=LoginUserID, Enabled = "Y", EvidFileSeq = seq , MTNO = mtNO, OperatorRemark = "", PlantID = PlantID, UpdateTime = ResultHelper.NowTime, ShowFIleName= fileName , SaveFileName= virtualPath }; fileModeles.Add(mtFileModel); #region 備份 //如已有備份則刪除 string bkFile = $"{filePath}BK_{fileName}"; if (ftp.FileExist(filePath, $"BK_{fileName}")) { ftp.Delete(bkFile); } if (ftp.FileExist(filePath,fileName)) { //上一個版本移動到備份 ftp.MovieFile(filePath, fileName, $"BK_{fileName}"); } #endregion // 保存文件 ftp.Upload(file, filePath, fileName); } // mtEvidFileBLL.Save(fileModeles); return Json(new { Success = true, Filepath = virtualPath, Message = "上傳成功!" }); } catch (Exception ex) { return Json(new { Success = false, Message = ex.Message }); } } else { return Json(new { Success = false, Message = "沒有要上傳的文件!!" }); } }
FTP 操作类
using System; using System.Text; using System.Net; using System.IO; using System.Data; using System.Configuration; using System.Web; namespace Lib.EMS.Common { public class FtpWeb { string ftpServerIP; string ftpRemotePath; string ftpUserID; string ftpPassword; string ftpURI; public FtpWeb() { DataTable dtIP = new DataTable(); dtIP = Lib.DAL.EMS.GetServerIP.GetFileServerIP(); string strIP = string.Empty; if (dtIP.Rows.Count > 0) { strIP = dtIP.Rows[0][0].ToString(); } else { throw new Exception("未獲取到FTP URL!請檢查系統設置"); } this.ftpRemotePath = string.Empty; this.ftpServerIP = strIP; this.ftpUserID = ConfigurationManager.AppSettings["FTPUser"]; this.ftpPassword = ConfigurationManager.AppSettings["FTPPwd"]; this.ftpURI = "ftp://" + ftpServerIP + "/"; } // 连接FTP //FtpRemotePath指定FTP连接成功后的当前目录, 如果不指定即默认为根目录 public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword) { ftpServerIP = FtpServerIP; ftpRemotePath = FtpRemotePath; ftpUserID = FtpUserID; ftpPassword = FtpPassword; ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; } // 上传 public void Upload(string localpath, string urlpath) { FileInfo fileInf = new FileInfo(localpath); string uri = ftpURI + urlpath; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = fileInf.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; FileStream fs = fileInf.OpenRead(); try { Stream strm = reqFTP.GetRequestStream(); contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } strm.Close(); fs.Close(); } catch (Exception ex) { throw ex; } } ////// 上傳 /// /// /// /// /// /// public bool Upload(HttpPostedFileBase fileInf, string utrlpath,string fileName) { bool isSuc = false; FtpWebRequest reqFTP; Stream strm = null; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(this.ftpURI+utrlpath + "/" + fileName)); reqFTP.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.KeepAlive = false; reqFTP.UseBinary = true; reqFTP.ContentLength = fileInf.ContentLength; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; Stream fs = fileInf.InputStream; try { strm = reqFTP.GetRequestStream(); contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } isSuc = true; } catch (Exception ex) { throw new Exception(ex.ToString()); } finally { strm.Close(); fs.Close(); } return isSuc; } // 下载 public void Download(string urlpath, string localpath) { FtpWebRequest reqFTP; try { FileStream outputStream = new FileStream(localpath, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + urlpath)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); long cl = response.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); } catch (Exception ex) { throw ex; } } // 删除文件 public void Delete(string urlpath) { try { string uri = ftpURI + urlpath; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; string result = String.Empty; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); long size = response.ContentLength; Stream datastream = response.GetResponseStream(); StreamReader sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); } catch (Exception ex) { throw ex; } } // 删除文件夹 public void RemoveDirectory(string urlpath) { try { string uri = ftpURI + urlpath; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory; string result = String.Empty; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); long size = response.ContentLength; Stream datastream = response.GetResponseStream(); StreamReader sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); } catch (Exception ex) { throw ex; } } //获取指定目录下明细(包含文件和文件夹) public string[] GetFilesDetailList(string urlpath) { string[] downloadFiles; try { bool getin = false; string uri = ftpURI + urlpath; StringBuilder result = new StringBuilder(); FtpWebRequest ftp; ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = ftp.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); string line = reader.ReadLine(); while (line != null) { getin = true; result.Append(line); result.Append("\n"); line = reader.ReadLine(); } if (getin) result.Remove(result.ToString().LastIndexOf("\n"), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); } catch (Exception ex) { downloadFiles = null; return downloadFiles; } } // 获取指定目录下文件列表(仅文件) public string[] GetFileList(string urlpath, string mask) { string[] downloadFiles; StringBuilder result = new StringBuilder(); FtpWebRequest reqFTP; try { string uri = ftpURI + urlpath; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.ListDirectory; WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); string line = reader.ReadLine(); while (line != null) { if (mask.Trim() != string.Empty && mask.Trim() != "*.*") { string mask_ = mask.Substring(0, mask.IndexOf("*")); if (line.Substring(0, mask_.Length) == mask_) { result.Append(line); result.Append("\n"); } } else { result.Append(line); result.Append("\n"); } line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf('\n'), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); } catch (Exception ex) { downloadFiles = null; if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。") { } return downloadFiles; } } // 获取指定目录下所有的文件夹列表(仅文件夹) public string[] GetDirectoryList(string urlpath) { string[] drectory = GetFilesDetailList(urlpath); string m = string.Empty; foreach (string str in drectory) { if (str == "") continue; int dirPos = str.IndexOf(" "); if (dirPos > 0) { /*判断 Windows 风格*/ m += str.Substring(dirPos + 5).Trim() + "\n"; } else if (str.Trim().Substring(0, 1).ToUpper() == "D") { /*判断 Unix 风格*/ string dir = str.Substring(54).Trim(); if (dir != "." && dir != "..") { m += dir + "\n"; } } } if (m[m.Length - 1] == '\n') m.Remove(m.Length - 1); char[] n = new char[] { '\n' }; return m.Split(n); //这样最后一个始终是空格了 } /// 判断指定目录下是否存在指定的子目录 // RemoteDirectoryName指定的目录名 public bool DirectoryExist(string urlpath, string RemoteDirectoryName) { string[] dirList = GetDirectoryList(urlpath); foreach (string str in dirList) { if (str.Trim() == RemoteDirectoryName.Trim()) { return true; } } return false; } public bool DirectoryExists(string directory) { bool directoryExists; directory = $"{ this.ftpURI}{directory}"; var request = (FtpWebRequest)WebRequest.Create(directory); request.Method = WebRequestMethods.Ftp.ListDirectory; request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword); try { using (request.GetResponse()) { directoryExists = true; } } catch (WebException) { directoryExists = false; } return directoryExists; } // 判断指定目录下是否存在指定的文件 //远程文件名 public bool FileExist(string urlpath, string RemoteFileName) { string[] fileList = GetFileList(urlpath, "*.*"); if (fileList == null) return false; foreach (string str in fileList) { if (str.Trim() == RemoteFileName.Trim()) { return true; } } return false; } // 创建文件夹 public void MakeDir(string urlpath) { FtpWebRequest reqFTP; try { // dirName = name of the directory to create. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + urlpath)); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { throw ex; } } /// ///创建文件夹 可多級創建 /// /// public void MakeDirByUrlPath(string urlpath) { string dirSub = string.Empty; for (int i = 0; i < urlpath.TrimEnd('/').Split('/').Length; i++) { dirSub += "/" + urlpath.Split('/')[i + 1]; if (!DirectoryExists(dirSub)) { MakeDir(dirSub); } } } // 获取指定文件大小 public long GetFileSize(string urlpath) { FtpWebRequest reqFTP; long fileSize = 0; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + urlpath)); reqFTP.Method = WebRequestMethods.Ftp.GetFileSize; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); fileSize = response.ContentLength; ftpStream.Close(); response.Close(); } catch (Exception ex) { throw ex; } return fileSize; } // 改名 public void ReName(string urlpath,string oldname, string newname) { FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + urlpath + oldname)); //源路径 reqFTP.Method = WebRequestMethods.Ftp.Rename; reqFTP.RenameTo = newname; //新名称 reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { throw ex; } } // 移动文件 public void MovieFile(string urlpath,string oldname, string newname) { ReName(urlpath, oldname, newname); } // 切换当前目录 /// true 绝对路径 false 相对路径 public void GotoDirectory(string DirectoryName, bool IsRoot) { if (IsRoot) { ftpRemotePath = DirectoryName; } else { ftpRemotePath += DirectoryName + "/"; } ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; } } }