ftp上传文件

摘要:
///上传文件//////////////protectedbootUpLoad(byte[]fileBytes,stringgorginalName,outs
    /// 上传文件
          /// </summary>
          /// <param name="fileBytes"></param>
          /// <param name="originalName"></param>
          /// <param name="msg"></param>
          /// <returns></returns>
        protected bool UpLoad(byte[] fileBytes, string originalName, out string newFileName, out string msg)
        {
            msg = "";
            newFileName = "";
            try
            {
                FTPUpFile ftp = new FTPUpFile();
                newFileName = ftp.UpFile(fileBytes, originalName);
                if (string.IsNullOrEmpty(newFileName))
                {
                    msg = "上传文件时出错!";
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false;
            }
        }

        /// <summary>
         /// FTP上传文件
         /// </summary>
        public class FTPUpFile
        {
            string Filetype = ConfigurationManager.AppSettings["FileType"];
            string ipaddress = ConfigurationManager.AppSettings["IPaddress"];
            string Username = ConfigurationManager.AppSettings["UserName"];
            string Password = ConfigurationManager.AppSettings["Password"];
            /// <summary>
              /// FTP上传文件
              /// </summary>
              /// <param name="filename">上传文件路径</param>
              /// <param name="ftpServerIP">FTP服务器的IP和端口</param>
              /// <param name="ftpPath">FTP服务器下的哪个目录</param>
              /// <param name="ftpUserID">FTP用户名</param>
              /// <param name="ftpPassword">FTP密码</param>
            public bool Upload(string filename, string ftpServerIP, string ftpPath, string ftpUserID, string ftpPassword)
            {
                FileInfo fileInf = new FileInfo(filename);
                string uri = "ftp://" + ftpServerIP + "/" + ftpPath + "/" + fileInf.Name;
                try
                {
                    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                    // ftp用户名和密码
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                    reqFTP.KeepAlive = false;
                    // 指定执行什么命令
                    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                    // 指定数据传输类型
                    reqFTP.UseBinary = true;
                    // 上传文件时通知服务器文件的大小
                    reqFTP.ContentLength = fileInf.Length;
                    //this.Invoke(InitUProgress, fileInf.Length);
                    // 缓冲大小设置为2kb
                    int buffLength = 4096;
                    byte[] buff = new byte[buffLength];
                    int contentLen;
                    // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
                    FileStream fs = fileInf.OpenRead();
                    // 把上传的文件写入流
                    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();
                    strm.Dispose();
                    fs.Close();
                    fs.Dispose();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
            /// <summary>
              /// 新建目录
              /// </summary>
              /// <param name="ftpPath"></param>
              /// <param name="dirName"></param>
            public void MakeDir(string ftpPath, string dirName, string username, string password)
            {
                try
                {
                    //实例化FTP连接
                    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + dirName));
                    // ftp用户名和密码
                    request.Credentials = new NetworkCredential(username, password);
                    // 默认为true,连接不会被关闭
                    request.KeepAlive = false;
                    //指定FTP操作类型为创建目录
                    request.Method = WebRequestMethods.Ftp.MakeDirectory;
                    //获取FTP服务器的响应
                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                    response.Close();
                }
                catch (Exception ex)
                {
                    //Respons
                }
            }
            /// <summary>
              /// 删除指定文件
              /// </summary>
              /// <param name="ftpPath"></param>
              /// <param name="dirName"></param>
              /// <param name="username"></param>
              /// <param name="password"></param>
            public void DeleteFile(string ftpPath, string username, string password)
            {
                try
                {
                    // string uri = "ftp://" + ftpServerIP + "/" + ftpPath + "/" + fileInf.Name;
                    //ftpPath = "ftp://192.168.1.111:2005/2012-12-05/20121206O5CATICE.docx";
                    //password = "111";
                    //username = "yuanluluoli";
                    //实例化FTP连接
                    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                    request.Method = WebRequestMethods.Ftp.DeleteFile;
                    // ftp用户名和密码
                    request.Credentials = new NetworkCredential(username, password);
                    // 默认为true,连接不会被关闭
                    request.KeepAlive = false;
                    //获取FTP服务器的响应
                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                    response.Close();
                }
                catch (Exception ex)
                {
                    //Respons
                }
            }
            /// <summary>
              /// 检查目录是否存在
              /// </summary>
              /// <param name="ftpPath">要检查的目录的路径</param>
              /// <param name="dirName">要检查的目录名</param>
              /// <returns>存在返回true,否则false</returns>
            public bool CheckDirectoryExist(string ftpPath, string dirName, string username, string password)
            {
                bool result = false;
                try
                {
                    //实例化FTP连接
                    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                    // ftp用户名和密码
                    request.Credentials = new NetworkCredential(username, password);
                    request.KeepAlive = false;
                    //指定FTP操作类型为创建目录
                    request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                    //获取FTP服务器的响应
                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                    StringBuilder str = new StringBuilder();
                    string line = sr.ReadLine();
                    while (line != null)
                    {
                        str.Append(line);
                        str.Append("|");
                        line = sr.ReadLine();
                    }
                    string[] datas = str.ToString().Split('|');
                    for (int i = 0; i < datas.Length; i++)
                    {
                        if (datas[i].Contains("<DIR>"))
                        {
                            int index = datas[i].IndexOf("<DIR>");
                            string name = datas[i].Substring(index + 5).Trim();
                            if (name == dirName)
                            {
                                result = true;
                                break;
                            }
                        }
                    }
                    sr.Close();
                    sr.Dispose();
                    response.Close();
                }
                catch (Exception)
                {
                    return false;
                }
                return result;
            }
            /// <summary>
              /// 上传文件
              /// </summary>
              /// <param name="buffer">文件的Byte数组</param>
              /// <param name="originalName">文件原始名字(带后缀名)</param>
              /// <param name="perStr">新文件名的前缀</param>
              /// <returns></returns>
            public string UpFile(byte[] buffer, string originalName, string perStr = "")
            {
                if (buffer == null || buffer.Length <= 0 || string.IsNullOrEmpty(originalName))
                    throw new ArgumentException("参数错误!");
                string filePathstr = string.Empty;
                string filepathsql = null;
                try
                {
                    string pathstr = perStr + DateTime.Now.ToString().Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "");
                    string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
                    filePathstr = "~/File/" + pathstr + rodumlist + Path.GetExtension(originalName);
                    //Stream sr = upfile.PostedFile.InputStream;
                    //byte[] file = new byte[sr.Length];
                    //sr.Read(file, 0, file.Length);
                    StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(filePathstr));
                    sw.BaseStream.Write(buffer, 0, buffer.Length);
                    sw.Flush(); sw.Close();
                    // file.SaveAs(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上
                    bool check;
                    string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
                    string uri = @"ftp://" + ipaddress + "/";
                    //检查是否存在此目录文件夹
                    if (CheckDirectoryExist(uri, ftpPath, Username, Password))
                    {
                        //存在此文件夹就直接上传
                        check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                    }
                    else
                    {
                        MakeDir(uri, ftpPath, Username, Password);//创建
                        check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                    }
                    //成功就更新
                    if (check)
                    {
                        filepathsql = ftpPath + "/" + pathstr + rodumlist + Path.GetExtension(originalName);
                    }
                    //检查是否存在此文件
                    if (File.Exists(HttpContext.Current.Server.MapPath(filePathstr)))
                    {
                        File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                    }
                    return filepathsql;
                }
                catch (Exception ex)
                {
                    File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                    throw ex;
                }
            }
            /// <summary>
              /// 上传文件
              /// 不修改名字及后缀名
              /// </summary>
              /// <param name="originalFilePath">上传文件的绝对路径</param>
              /// <returns></returns>
            public string UpFile(string originalFilePath)
            {
                if (string.IsNullOrEmpty(originalFilePath))
                    throw new ArgumentException("参数错误!");
                string filepathsql = null;
                try
                {
                    //检查是否存在此文件
                    if (!File.Exists(originalFilePath))
                        throw new Exception("文件不存在!");
                    //Stream sr = upfile.PostedFile.InputStream;
                    //byte[] file = new byte[sr.Length];
                    //sr.Read(file, 0, file.Length);
                    // file.SaveAs(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上
                    bool check;
                    string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
                    string uri = @"ftp://" + ipaddress + "/";
                    //检查是否存在此目录文件夹
                    if (CheckDirectoryExist(uri, ftpPath, Username, Password))
                    {
                        //存在此文件夹就直接上传
                        check = Upload(originalFilePath, ipaddress, ftpPath, Username, Password);
                    }
                    else
                    {
                        MakeDir(uri, ftpPath, Username, Password);//创建
                        check = Upload(originalFilePath, ipaddress, ftpPath, Username, Password);
                    }
                    //成功就更新
                    if (check)
                    {
                        filepathsql = ftpPath + "/" + Path.GetFileName(originalFilePath);
                    }
                    //检查是否存在此文件
                    if (File.Exists(originalFilePath))
                    {
                        File.Delete(originalFilePath);
                    }
                    return filepathsql;
                }
                catch (Exception ex)
                {
                    //File.Delete(originalFilePath);
                    throw ex;
                }
            }
            public string Ftp_Up(HtmlInputFile upfile)
            {
                //Encrypt En = new Encrypt();
                string filePathstr = string.Empty;
                string filepathsql = null;
                try
                {
                    string pathstr = DateTime.Now.ToString().Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "");
                    string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
                    filePathstr = "~/File/" + pathstr + rodumlist + Path.GetExtension(upfile.PostedFile.FileName);
                    Stream sr = upfile.PostedFile.InputStream;
                    byte[] file = new byte[sr.Length];
                    sr.Read(file, 0, file.Length);
                    StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(filePathstr));
                    sw.BaseStream.Write(file, 0, file.Length);
                    sw.Flush(); sw.Close(); sr.Flush(); sr.Close();
                    // file.SaveAs(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上
                    bool check;
                    string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
                    string uri = @"ftp://" + ipaddress + "/";
                    //检查是否存在此目录文件夹
                    if (CheckDirectoryExist(uri, ftpPath, Username, Password))
                    {
                        //存在此文件夹就直接上传
                        check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                    }
                    else
                    {
                        MakeDir(uri, ftpPath, Username, Password);//创建
                        check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                    }
                    //成功就更新
                    if (check)
                    {
                        filepathsql = ftpPath + "/" + pathstr + rodumlist + Path.GetExtension(upfile.PostedFile.FileName);
                    }
                    //检查是否存在此文件
                    if (File.Exists(HttpContext.Current.Server.MapPath(filePathstr)))
                    {
                        File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                    }
                    return filepathsql;
                }
                catch (Exception)
                {
                    File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                    return filepathsql;
                    // Response.Write("<script>alert(" + ex.Message + ");</script>");
                }
            }
            /// <summary>
              /// 上传
              /// </summary>
              /// <param name="file"></param>
              /// <returns></returns>
            public string Ftp_Up(HttpPostedFileBase postedFile)
            {
                string filePathstr = string.Empty;
                string filepathsql = null;
                try
                {
                    string pathstr = DateTime.Now.ToString("yyyyMMddHHmmss");
                    string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
                    string filename = System.IO.Path.GetFileName(postedFile.FileName);
                    string eExtension = Path.GetExtension(filename);
                    string strLocation = HttpContext.Current.Server.MapPath("~/File/");
                    filePathstr = strLocation + pathstr + rodumlist + eExtension;
                    postedFile.SaveAs(filePathstr);
                    bool check;
                    string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
                    string uri = @"ftp://" + ipaddress + "/";
                    //检查是否存在此目录文件夹
                    if (CheckDirectoryExist(uri, ftpPath, Username, Password))
                    {
                        //存在此文件夹就直接上传
                        check = Upload(filePathstr, ipaddress, ftpPath, Username, Password);
                    }
                    else
                    {
                        MakeDir(uri, ftpPath, Username, Password);//创建
                        check = Upload(filePathstr, ipaddress, ftpPath, Username, Password);
                    }
                    //成功就更新
                    if (check)
                    {
                        filepathsql = ftpPath + "/" + pathstr + rodumlist + eExtension;
                    }
                    //检查是否存在此文件
                    if (File.Exists(filePathstr))
                    {
                        File.Delete(filePathstr);
                    }
                    return filepathsql;
                }
                catch (Exception ex)
                {
                    //检查是否存在此文件
                    if (File.Exists(filePathstr))
                    {
                        File.Delete(filePathstr);
                    }
                    return "";
                    // Response.Write("<script>alert(" + ex.Message + ");</script>");
                }
            }
            /// <summary>
              /// FTP下载文件在服务器目录
              /// </summary>
              /// <param name="pathname">本地保存目录路径和文件名称</param>
              /// <param name="filename">FTP目录路径和文件名称</param>
              /// <returns></returns>
            public bool FileDown(string pathname, string filename)
            {
                string uri = "ftp://" + ipaddress + "/" + filename;
                string FileName = pathname;//本地保存目录
                                           //创建一个文件流
                FileStream fs = null;
                Stream responseStream = null;
                try
                {
                    //创建一个与FTP服务器联系的FtpWebRequest对象
                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(uri));
                    //连接登录FTP服务器
                    request.Credentials = new NetworkCredential(Username, Password);
                    request.KeepAlive = false;
                    //设置请求的方法是FTP文件下载
                    request.Method = WebRequestMethods.Ftp.DownloadFile;
                    //获取一个请求响应对象
                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                    //获取请求的响应流
                    responseStream = response.GetResponseStream();
                    //判断本地文件是否存在,如果存在,则打开和重写本地文件
                    if (File.Exists(FileName))
                        fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite);
                    //判断本地文件是否存在,如果不存在,则创建本地文件
                    else
                    {
                        fs = File.Create(FileName);
                    }
                    if (fs != null)
                    {
                        int buffer_count = 65536;
                        byte[] buffer = new byte[buffer_count];
                        int size = 0;
                        while ((size = responseStream.Read(buffer, 0, buffer_count)) > 0)
                        {
                            fs.Write(buffer, 0, size);
                        }
                        fs.Flush();
                        fs.Close();
                        responseStream.Close();
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    if (fs != null)
                        fs.Close();
                    if (responseStream != null)
                        responseStream.Close();
                }
            }

              /// <summary>
              /// 保存和上传图片
              /// </summary>
              /// <param name="imgtwo">需要上传图片</param>
              /// <param name="date"></param>
              /// <returns>文件路径</returns>
            public string SaveUploadImg(Bitmap imgtwo)
            {
                string filePathstr = string.Empty;
                string filepathsql = null;
                try
                {
                    string pathstr = DateTime.Now.ToString().Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "");
                    string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
                    filePathstr = "~/File/" + pathstr + rodumlist + ".jpg";
                    imgtwo.Save(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上
                    bool check;
                    string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
                    string uri = @"ftp://" + ipaddress + "/";
                    //检查是否存在此目录文件夹
                    if (CheckDirectoryExist(uri, ftpPath, Username, Password))
                    {
                        //存在此文件夹就直接上传
                        check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                    }
                    else
                    {
                        MakeDir(uri, ftpPath, Username, Password);//创建
                        check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
                    }
                    //成功就更新
                    if (check)
                    {
                        filepathsql = ftpPath + "/" + pathstr + rodumlist + ".jpg";
                    }
                    //检查是否存在此文件
                    if (File.Exists(HttpContext.Current.Server.MapPath(filePathstr)))
                    {
                        File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                    }
                    imgtwo.Dispose();
                    return filepathsql;
                }
                catch (Exception ex)
                {
                    File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
                    return filepathsql;
                }
            }
            #region
            /// <summary>
              /// 文件大小
              /// </summary>
            public bool _File_Length(int ContentLength)
            {
                bool length = false;
                int FileLen = ContentLength;
                if (FileLen > 2048 * 1024 == false)//不能超过2M
                {
                    length = true;
                }
                return length;
            }
            #endregion
            //用来获取文件类型
            public bool File_PastFileName(string fileName)
            {
                //bmp, doc, docx, gif, jpg, jpeg, pdf, png, tif, tiff
                bool isnot = true;
                string ext = Path.GetExtension(fileName);
                string[] type = Filetype.Split(';');
                for (int i = 0; i < type.Length; i++)
                {
                    if (type[i].ToLower() == ext.ToLower())
                    {
                        isnot = false;
                        break;
                    }
                }
                return isnot;
            }
        }

    }

    internal class GeneralHelper
    {
        internal static string GetMixPwd(int v)
        {
            throw new NotImplementedException();
        }
    }

  

免责声明:文章转载自《ftp上传文件》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇IP地址转换、主机大小端、htonl、ntohl实现GRUB配置与应用,启动故障分析解决下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

简单的linux内核移植知识

Linux内核的移植(ARM)总结 虽然没有干过这个工作,不过听说内核移植从来就不是一个人的事。通常都是由一个百人的团队去做的,所以这里讲的仅仅是最简单的一些。往往不去关心原理,只是懂得如何操作罢了。 知识储备 在学习移植之前,需要知道的知识和概念,操作系统启动的过程,bootloader,内核,根文件系统等。 计算机结构:两层结构:软件,硬件。 四层结构:...

文件与目录差异对比模块filecmp

简介 当我们进行代码审计或校验备份结果时,往往需要检查原始与目标目录的文件一致性,python的标准库已经自带了满足此需求的模块filecmp。filecmp可以实现文件、目录、遍历子目录的差异对比功能。比如报告中输出目标目录比原始多出的文件或子目录,即使文件同名也会判断是否为同一个文件(内容级对比)等,python2.3以上版本自带了filecmp模块...

C#获取类库(DLL)的绝对路径

C#中当我们在写公共的类库的时候难免会调用一些xml配置文件,而这个配置文件的路径则非常重要,常用的方式就是写在web.config中,而我们也可以将配置文件直接放在dll的同级目录,那么怎么获得当前dll的同级目录呢,使用下面方法即可。 /// <summary> /// 获取Assembly的运行路径 /// </summary&...

日志采集框架Flume以及Flume的安装部署(一个分布式、可靠、和高可用的海量日志采集、聚合和传输的系统)

 Flume支持众多的source和sink类型,详细手册可参考官方文档,更多source和sink组件 http://flume.apache.org/FlumeUserGuide.html Flume官网入门指南:  1:Flume的概述和介绍: (1):Flume是一个分布式、可靠、和高可用的海量日志采集、聚合和传输的系统。(2):Flume可...

ListView数据动态更新

      经常会用到数据与前台控件绑定相关的问题,一直知道要用委托(代理)但每次都忘,而且每次都百度了一遍又一遍,就是不长记性,这次一定好好记下来下次就不会忘了。       后台数据与前台绑定主要分为两步:       第一步把要绑定的数据定义为一个数据集合或对象绑定到List中,方便调用: public class TestCase:INotifyP...

使用replaceAll实现字符串替换

使用replaceAll实现字符串替换,具体要求为将字符串“abc123bcd45ef6g7890”中的数字替换成汉字“数字”,如果是连续的数字那么替换为一个汉字“数字”。 在Java api中的String类提供了replaceAll方法,实现将字符串中匹配正则表达式的字符串替换成其它字符串,replaceAll方法的声明如下所示: String rep...