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));                  
                    List<Lib.Model.EMS.Spart.MTEvidFile> fileModeles = new List<Lib.Model.EMS.Spart.MTEvidFile>();
                    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 = "沒有要上傳的文件!!" });
            }                   
        }
View Code

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;
            }
        }

        /// <summary>
        /// 上傳
        /// </summary>
        /// <param name="fileInf"></param>
        /// <param name="strRemotePath"></param>
        /// <param name="strFtpID"></param>
        /// <param name="strFtpPwd"></param>
        /// <returns></returns>
        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("<DIR>");
                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;
            }
        }

        /// <summary>
        ///創建文件夾 可多級創建
        /// </summary>
        /// <param name="urlpath"></param>
        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);
        }

        // 切換當前目錄
        /// <param name="IsRoot">true 絕對路徑   false 相對路徑</param>
        public void GotoDirectory(string DirectoryName, bool IsRoot)
        {
            if (IsRoot)
            {
                ftpRemotePath = DirectoryName;
            }
            else
            {
                ftpRemotePath += DirectoryName + "/";
            }
            ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
        }
    }
}
View Code

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章