Asp.Net搭建FTP、SFTP上传文件服务

目录

搭建FTP服务

搭建SFTP服务


搭建FTP服务

1.IIS搭建FTP详细教程

2.FileZilla Server搭建FTP详细教程

* 官方下载地址(里面有服务端和客户端根据需求下载)
  https://www.filezilla.cn/download
  
* 傻瓜式安装服务器端,可以更换安装路径
  
* 配置服务端
  服务端运行时有小窗口弹出,需要配置主机、端口、密码(根据实际情况)
  本机:localhost 14147 password
  esc服务器:192.168.0.1 14147  password
  
* 配置访问Ftp服务的用户和共享文件夹
  点击菜单栏 设置 用户 或者 点击菜单栏 小人头图标
  添加——>输入账户名称——>确定 ——>勾选密码——>输入密码——>点击确定
  弹窗创建共享文件夹——>添加——>选择创建好的文件夹——>勾选文件夹、目录权限——>确定
  
* 阿里云服务器要配置安全组
  比如登录FTP服务的14147一直往后延伸10个IP 14147-14157

* 服务端设置 (本地搭建的无需设置)
  设置——>被动模式设置——>输入自定义端口范围 14147-14157

3..Net 4.0代码实现过程

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace SyncFileTool.Utils
{
    /// <summary>
    ///    FTP帮助类 
    /// </summary>
    public class FTPUtil
    {
        /// <summary>
        /// WebClient连接FTP服务上载文件
        /// </summary>
        /// <param name="ftpUrl">ftp 的ip地址</param>
        /// <param name="ftpUserName">访问ftp账户名</param>
        /// <param name="ftpPassword">访问ftp账户密码</param>
        /// <param name="fileName">ftp文件名</param>
        /// <param name="localFile">本地文件(绝对路径)</param>
        public static void WebClientUploadFileToFtp(string ftpUrl,string ftpUserName,string ftpPassword, string fileName, string localFile)
        {
            try
            {
                Console.WriteLine($"开始往FTP://{ftpUrl}上传{fileName}");
                using (var client = new WebClient())
                {
                    client.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
                    client.Encoding = System.Text.Encoding.GetEncoding("GB2312");
                    //上传文件
                    client.UploadFile($"ftp://{ftpUrl}/{fileName}", WebRequestMethods.Ftp.UploadFile, localFile);
                }

                Console.WriteLine($"文件:{fileName} 上传到FTP://{ftpUrl}/成功");
                LogHelper.Info($"文件:{fileName} 上传到FTP://{ftpUrl}/成功");
            }
            catch (Exception ex)
            {
                LogHelper.Error($"文件:{fileName} 上传到FTP://{ftpUrl}/失败;错误信息:{ex.Message}");
            }
        }

        /// <summary>
        /// 判断Ftp上该文件是否存在
        /// </summary>
        /// <param name="ftpUrl">ftp 的ip地址</param>
        /// <param name="ftpUserName">访问ftp账户名</param>
        /// <param name="ftpPassword">访问ftp账户密码</param>
        /// <param name="filePath">本地文件(绝对路径)</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static bool FtpWebRequestGetFile(string ftpUrl, string ftpUserName, string ftpPassword, string filePath, string fileName)
        {
            Console.WriteLine($"检查文件:{fileName}是否存在");
            try
            {
                FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create($"ftp://{ftpUrl}/{fileName}");
                ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
                ftpRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
                using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
                {
                    //判断ftp文件是否存在
                    var statusCode = ftpResponse.StatusCode;
                    if (statusCode == FtpStatusCode.FileStatus)
                    {
                        //获取本地文件大小跟ftp服务器文件进行对比 不一致直接覆盖
                        FileInfo file = new FileInfo(filePath);
                        if (file.Length != ftpResponse.ContentLength)
                        {
                            return false;
                        }

                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"检查文件:{fileName} 时发生异常;错误信息:{ex.Message}");
            }
            return false;
        }

    }
}

搭建SFTP服务

1.SFTP搭建详细过程

2.通过Nuget下载SSH.Net包

3..Net4.0 代码实现


using Bingosoft.Common.AntiAttack.Xss;

using Renci.SshNet;

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SyncFileTool.Utils
{
    /// <summary>
    /// SFTP静态工具类
    /// </summary>
    public static class SftpStaticUtil
    {
        #region 字段或属性
        private static SftpClient sftp;
        /// <summary>
        /// SFTP连接状态
        /// </summary>
        public static bool Connected { get { return sftp.IsConnected; } }

        //SFTP服务器IP
        private static string ip = ConfigurationManager.AppSettings["SftpIp"];
        //SFTP服务器账号
        private static string userName = ConfigurationManager.AppSettings["SftpUserName"];
        //SFTP服务器密码
        private static string cipher = ConfigurationManager.AppSettings["SftpCipher"];
        //SFTP服务器端口
        private static string port = ConfigurationManager.AppSettings["SftpPort"];
        #endregion

        #region 初始化连接
        /// <summary>
        /// 初始化连接
        /// </summary>
        static SftpStaticUtil()
        {
            string clearText = DesUtil.GetPassword(cipher);
            sftp = new SftpClient(ip, Int32.Parse(port), userName, clearText);
            Connect();
        }

        #endregion

        #region 连接SFTP
        /// <summary>
        /// 连接SFTP
        /// </summary>
        /// <returns>true成功</returns>
        public static bool Connect()
        {
            try
            {
                if (!Connected)
                {
                    sftp.Connect();
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("连接SFTP失败,原因:{0}", ex.Message));
            }
        }
        #endregion

        #region 断开SFTP
        /// <summary>
        /// 断开SFTP
        /// </summary> 
        public static void Disconnect()
        {
            try
            {
                if (sftp != null && Connected)
                {
                    sftp.Disconnect();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.Message));
            }
        }
        #endregion

        #region  SFTP上传文件
        /// <summary>
        /// SFTP上传文件
        /// </summary>
        /// <param name="localFile">本地文件全路径 例:G:\\Project\\logo.png</param>
        /// <param name="remotePath">远程路径  例:/logo.png</param>
        public static void Put(string localFile, string remotePath)
        {
            Console.WriteLine($"开始往FTP://{ip}上传{remotePath}");
            try
            {
                using (Stream input = File.OpenRead(System.Web.HttpUtility.HtmlDecode(AntiXss.HtmlEncode(localFile)).Replace("..", "").Replace("../", "").Replace("~/", "")))
                {
                    Connect();
                    sftp.UploadFile(input, remotePath);
                    Disconnect();
                }
                Console.WriteLine($"文件:{remotePath} 上传到FTP://{ip}/成功");
                LogHelper.Info($"文件:{remotePath} 上传到FTP://{ip}/成功");
            }
            catch (Exception ex)
            {
                LogHelper.Error($"文件上传到sftp失败;错误信息:{ex.Message}");
            }
        }
        #endregion

        #region SFTP获取文件
        /// <summary>
        /// SFTP获取文件
        /// </summary>
        /// <param name="remotePath">远程路径</param>
        /// <param name="localPath">本地路径</param>
        public static void Get(string remotePath, string localPath)
        {
            try
            {
                Connect();
                var byt = sftp.ReadAllBytes(remotePath);
                Disconnect();
                File.WriteAllBytes(localPath, byt);
            }
            catch (Exception ex)
            {
                LogHelper.Error(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
            }

        }
        #endregion

        #region SFTP判断文件是否存在
        /// <summary>
        /// SFTP获取文件
        /// </summary>
        /// <param name="remotePath">远程路径</param>
        /// <param name="localFile">本地路径</param>
        public static bool Exsit(string remotePath, string localFile)
        {
            Console.WriteLine($"检查文件:{remotePath}是否存在");
            try
            {
                Connect();
                var byt = sftp.ReadAllBytes(remotePath);
                Disconnect();

                FileInfo fileInfo = new FileInfo(System.Web.HttpUtility.HtmlDecode(AntiXss.HtmlEncode(localFile)).Replace("..", "").Replace("../", "").Replace("~/", ""));
                if (fileInfo.Length != byt.Length)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                if (ex.Message.Equals("Permission denied"))
                {
                    LogHelper.Error($"远程检查文件:{remotePath}不存在,开启同步。");
                }
                else
                {
                    LogHelper.Error($"检查文件:{remotePath},异常原因:{ex.Message}");
                }
            }
            return false;
        }
        #endregion

        #region 删除SFTP文件
        /// <summary>
        /// 删除SFTP文件 
        /// </summary>
        /// <param name="remoteFile">远程路径</param>
        public static void Delete(string remoteFile)
        {
            try
            {
                Connect();
                sftp.Delete(remoteFile);
                Disconnect();
            }
            catch (Exception ex)
            {
                LogHelper.Error(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
            }
        }
        #endregion
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C#写的ASP.NET上传到FTP上,文件,文件都可以。 首先,选择本地文件或者文件,然后点击上传按钮以后,有一个压缩过程,该过程也有一个实时更新的进度条,并可以显示压缩所需的实时更新的剩余时间,压缩完成以后上传,上传也是有一个实时更新的进度条,显示剩余上传所需时间。上传完成以后显示压缩的时间、上传的时间和总共所需的时间。 根据文件流上传,根据文件流进度做的进度条,是真的实实在在的进度条。 代码都有详细的注释,例如: private string ftpUser = "Administrator"; //ftp用户名 private string ftpPassword = "123456"; //ftp密码 public TimeSpan t; //加载进度条总时间 private DateTime startTotalTimeFtp = System.DateTime.Now; private DateTime endTotalTimeFtp = System.DateTime.Now; //压缩用时(为传值做准备) //public TimeSpan zipTime; //定义开始时间、结束时间和之间的时间段,以此来估计完成所需剩余时间 DateTime startTime = System.DateTime.Now; DateTime endTime = System.DateTime.Now; TimeSpan TimeSp; //定义剩余时间 string surPlusTime = string.Empty; //判断是否小于1秒所用 int Ti = 0; //实例化类TimeSpanClass TimeSpanClass timeSpanClass = new TimeSpanClass(); 进度条可以实时动态更新,显示剩余时间,剩余时间也跟随进度条实时动态更新,上传完成显示上传时间。 再次声明,版权所有(花费本人好几个月的心血研究真实的进度条),保证进度条为真正按照文件流的进度所进行,如有问题,可与本人联系!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值