.NET mvc实现图片上传功能,保存到本地,ftp等地方及获取图片

1.前端实用layui的上传功能
2.后端.net 可以实现上传保存到本地,到ftp,甚至是七牛云,我之前有文章提及到。
3,获取图片,有时我们可能对图片做权限控制,所以会写一个接口获取图片,实现控制图片的作用
获取图片包含从本地获取getImage 从http远程获取 getImageHttp ,从ftp获取getImageFtp
源码链接放在文末
效果图:
.NET mvc实现图片上传功能,保存到本地,ftp等地方及获取图片_第1张图片
获取图片效果图及url 路径 也可以直接浏览器中直接请求查看

在这里插入图片描述
.NET mvc实现图片上传功能,保存到本地,ftp等地方及获取图片_第2张图片
项目整体增加的如下
.NET mvc实现图片上传功能,保存到本地,ftp等地方及获取图片_第3张图片

前端代码Image.cshtml


@{
    ViewBag.Title = "Image";
}

@section scripts{



}
<link href="~/dist/css/layui.css" rel="stylesheet" />
<style>

    .layui-upload-img {
        width: 92px;
        height: 92px;
    }

</style>



<div style="margin-top:200px;">

    <div class="layui-upload">
        <button type="button" class="layui-btn" id="test1">上传图片</button>
        <div class="layui-upload-list">
            <img class="layui-upload-img" id="demo1">
            <p id="demoText"></p>
        </div>
        <div style="width: 95px;">
            <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
                <div class="layui-progress-bar" lay-percent=""></div>
            </div>
        </div>

    </div>

    <a name="list-progress"> </a>

    <div style="margin-top: 10px;">

        <!-- 示例-970 -->
        <!--
        <ins class="adsbygoogle"
        style="display:inline-block;width:970px;height:90px"
        data-ad-client="ca-pub-6111334333458862"
        data-ad-slot="3820120620"></ins>
        -->

    </div>
</div>
<script src="~/dist/layui.js"></script>
<script>
    layui.use(['upload', 'element', 'layer'], function () {
        var $ = layui.jquery
            , upload = layui.upload
            , element = layui.element
            , layer = layui.layer;

        //常规使用 - 普通图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            , url: '/Home/UpLoad' //此处用的是第三方的 http 请求演示,实际使用时改成您自己的上传接口即可。
            , before: function (obj) {
                //预读本地文件示例,不支持ie8
                obj.preview(function (index, file, result) {
                   
                    $('#demo1').attr('src', result); //图片链接(base64)
                });

                element.progress('demo', '0%'); //进度条复位
                layer.msg('上传中', { icon: 16, time: 0 });
            }
            , done: function (res) {
                //如果上传失败
                if (res.code > 0) {
                    return layer.msg('上传失败');
                }
                return layer.msg('上传成功,文件名'+res.fileName);
                //上传成功的一些操作
                //……
                $('#demoText').html(''); //置空上传失败的状态
            }
            , error: function () {
                //演示失败状态,并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
            //进度条
            , progress: function (n, elem, e) {
                element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
                if (n == 100) {
                    layer.msg('上传完毕', { icon: 1 });
                }
            }
        });

       

    });
</script>

后端控制器重要代码 展示上传保存的功能


```csharp
  public ActionResult UpLoad()
        {
            
            //  获得上传请求
            var file = Request.Files[0];
            //  初始化图片资源
            System.IO.Stream MyStream = file.InputStream;
            System.Drawing.Image original = System.Drawing.Image.FromStream(MyStream);
             String basepath = AppDomain.CurrentDomain.BaseDirectory;
            String extenName = Path.GetExtension(file.FileName);
            String path = Path.Combine(basepath, "Image");
            if (!Directory.Exists(path)) 
            {
                Directory.CreateDirectory(path);
            }
            String  imageName=Guid.NewGuid().ToString("N")+extenName;
            String savepath= Path.Combine(path, imageName);
            // 保存图片到本地
            original.Save(savepath);

            original.Dispose();
            //以下保存到ftp
            //MemoryStream ms = new MemoryStream();
            //MyStream.CopyTo(ms);

            //string ftpurl = "";

            //string tagName = "result";
            //String url = Path.Combine(ftpurl, imageName);
            //FTPHelper ftpHelper = new FTPHelper("ftp:uri", "uername", "password");

          
            //if (!ftpHelper.DirectoryExist(url, tagName))
            //{
            //    ftpHelper.CreateDirectory(ftpurl + tagName);
            //}
 
            //if (!ftpHelper.Upload(ms, url))
            //{
            //    return Json(new   { code=1, ErrorMessage = string.Format("上传图片失败!") });
            //}

            //ms.Dispose();




            return Json(new { code=0,fileName= imageName });

        }


获取图片接口代码

```csharp
   public ActionResult GetImageFtp(String imageName)
        {

            string ftpurl = "";
            String url =Path.Combine(ftpurl, imageName);
            if (string.IsNullOrEmpty(url)) return new EmptyResult();
            using (MemoryStream mStream = new MemoryStream())
            {
                FtpWebRequest reqFtp;
                reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
                //登录ftp服务器,ftpName:账户名,ftpPwd:密码
                //  reqFtp.Credentials = new NetworkCredential(ftpName, ftpPwd);
                reqFtp.UseBinary = true;  //该值指定文件传输的数据类型。
                reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
                FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.CopyTo(mStream);
                return File(mStream.ToArray(), "image/jpeg"); ;
            }

        }

        public ActionResult GetImageHttp()
        {

            String url = "https://img1.baidu.com/it/u=413643897,2296924942&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500";
            using (MemoryStream ms = new MemoryStream())
            {
                int BytesToRead = 100;
                if (!string.IsNullOrEmpty(url))
                {
                    WebRequest request = WebRequest.Create(new Uri(url, UriKind.Absolute));
                    request.Timeout = -1;
                    WebResponse response = request.GetResponse();
                    Stream responseStream = response.GetResponseStream();
                    responseStream.CopyTo(ms);
                }
                return File(ms.ToArray(), "image/jpeg");
            }
        }

        public ActionResult GetImage(String imagename)
        {
            String basepath = AppDomain.CurrentDomain.BaseDirectory;

            String path = Path.Combine(basepath, "Image", imagename);
            
            FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);

            using (MemoryStream ms = new MemoryStream())
            {

                fileStream.CopyTo(ms);
                return File(ms.ToArray(), "image/jpeg");
            }
         
        }

操作ftp的封装类

    public class FTPHelper
    {
        private string ftpUri;  //ftp服务器地址
        private string ftpName;  //ftp帐户
        private string ftpPwd;  //ftp密码
        private FtpWebRequest ftpRequest;  //请求
        private FtpWebResponse ftpResponse;  //响应

        public FTPHelper(string uri, string name, string password)
        {
            this.ftpUri = uri;
            this.ftpName = name;
            this.ftpPwd = password;
        }

        /// 
        /// 连接类
        /// 
        /// ftp地址
        private void Conn(string uri)
        {
            ftpRequest = (FtpWebRequest)WebRequest.Create(uri);
            //登录ftp服务器,ftpName:账户名,ftpPwd:密码
            ftpRequest.Credentials = new NetworkCredential(ftpName, ftpPwd);
            ftpRequest.UseBinary = true;  //该值指定文件传输的数据类型。
        }

        /// 
        /// 删除文件
        /// 
        /// 文件名
        public void DeleteFileName(string fileName)
        {
            string uri = ftpUri + "/" + fileName;
            Conn(uri);
            try
            {
                ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpResponse.Close();

            }
            catch (Exception exp)
            {
                //   // ErrorLog.GetInstance().Write(exp.Message);
                throw new Exception(exp.Message);
            }
        }



        /// 
        /// 删除ftp上目录
        /// 
        /// 
        public void RemoveDir(string dirName)
        {
            string uri = ftpUri + "/" + dirName;
            Conn(uri);
            try
            {
                ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpResponse.Close();

            }
            catch (Exception exp)
            {
                // // ErrorLog.GetInstance().Write(exp.Message);
                throw new Exception(exp.Message);
            }
        }


        /// 
        /// 上传文件,使用FTPWebRequest、FTPWebResponse实例
        /// 
        /// ftp地址
        /// 文件名
        /// 文件内容
        /// 传出参数,返回传输结果
        public void UploadFile(string uri, string fileName, byte[] fileData, out string msg)
        {
            string URI = uri.EndsWith("/") ? uri : uri + "/";
            URI += fileName;
            //连接ftp服务器
            Conn(URI);
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            ftpRequest.ContentLength = fileData.Length; //上传文件时通知服务器文件的大小
            try
            {
                //将文件流中的数据(byte[] fileData)写入请求流
                using (Stream ftpstream = ftpRequest.GetRequestStream())
                {
                    ftpstream.Write(fileData, 0, fileData.Length);
                }

                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); //响应
                msg = ftpResponse.StatusDescription; //响应状态
                ftpResponse.Close();
            }
            catch (Exception exp)
            {
                msg = "Failed to upload:" + exp.Message;
                // // ErrorLog.GetInstance().Write(exp.Message);
                throw new Exception(exp.Message);
            }
        }

        /// 
        /// 上传文件,使用WebClient类
        /// 
        /// ftp地址
        /// 文件名
        /// 文件内容
        /// 传出参数,输出传输结果
        public void UploadFileByWebClient(string uri, string fileName, byte[] fileData, out string msg)
        {
            string URI = uri.EndsWith("/") ? uri : uri + "/";
            URI += fileName;

            try
            {
                WebClient client = new WebClient();
                //登录FTP服务
                client.Credentials = new NetworkCredential(ftpName, ftpPwd);
                client.UploadData(URI, "STOR", fileData); //指定为ftp上传方式
                msg = "上传成功!";
            }
            catch (Exception exp)
            {
                msg = "Failed to upload:" + exp.Message;
                //  // ErrorLog.GetInstance().Write(exp.Message);
                throw new Exception(exp.Message);
            }
        }

        /// 
        /// 下载文件,使用FTPWebRequest、FTPWebResponse实例
        /// 
        /// ftp地址
        /// 目标文件存放地址
        /// 传出参数,返回传输结果
        public void DownloadFile(string uri, string destinationDir, out string msg)
        {
            string fileName = Path.GetFileName(uri);
            string destinationPath = Path.Combine(destinationDir, fileName);

            try
            {
                //连接ftp服务器
                Conn(new Uri(ftpUri + uri).ToString());

                using (FileStream outputStream = new FileStream(destinationPath, FileMode.OpenOrCreate))
                {
                    using (ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
                    {
                        //将响应流中的数据写入到文件流
                        using (Stream ftpStream = ftpResponse.GetResponseStream())
                        {
                            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);
                            }
                        }
                        msg = ftpResponse.StatusDescription;
                    }
                }
            }
            catch (Exception exp)
            {
                msg = "Failed to download:" + exp.Message;
                //  // ErrorLog.GetInstance().Write(exp.Message);
                throw new Exception(exp.Message);
            }
        }
        public byte[] DownloadFile()
        {
            try
            {
                WebClient client = new WebClient();
                client.Credentials = new NetworkCredential(this.ftpName, this.ftpPwd);
                byte[] responseData = client.DownloadData(this.ftpUri);
                return responseData;
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }


        /// 
        /// 文件下载,使用WebClient类
        /// 
        /// ftp服务地址
        /// 存放目录
        public void DownloadFileByWebClient(string uri, string destinationDir)
        {

            string fileName = Path.GetFileName(uri);
            string destinationPath = Path.Combine(destinationDir, fileName);

            try
            {
                WebClient client = new WebClient();
                client.Credentials = new NetworkCredential(this.ftpName, this.ftpPwd);

                byte[] responseData = client.DownloadData(uri);

                using (FileStream fileStream = new FileStream(destinationPath, FileMode.OpenOrCreate))
                {
                    fileStream.Write(responseData, 0, responseData.Length);
                }

            }
            catch (Exception exp)
            {
                //  // ErrorLog.GetInstance().Write(exp.Message);
                throw new Exception(exp.Message);
            }
        }

        /// 
        /// 创建文件夹
        /// 
        /// 
        public void CreateDirectory(string path)
        {
            //int pos = path.LastIndexOf("/");
            //path = path.Substring(0, pos);
            //string[] dirs = GetFileList(Path.GetDirectoryName(path));
            //if (dirs == null || dirs.Length == 0)
            //{
            try
            {
                //    if (reqFTP != null) return;
                // 根据uri创建FtpWebRequest对象
                var reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
                // 指定数据传输类型
                reqFTP.UseBinary = true;
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(ftpName, ftpPwd);
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                //    // ErrorLog.GetInstance().Write(ex);
            }
            //}

            return;

        }


        /// 
        /// 遍历文件
        /// 
        public ArrayList GetListDirectoryDetails()
        {
            ArrayList fileInfo = new ArrayList();
            try
            {
                Conn(ftpUri);

                //获取 FTP 服务器上的文件的详细列表的 FTP LIST 协议方法
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                try
                {
                    ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); //响应
                }
                catch (System.Net.WebException e)
                {
                    //   // ErrorLog.GetInstance().Write(e.Message);
                    //  // ErrorLog.GetInstance().Write(e.Message);
                    throw new Exception(e.Message);
                }
                catch (System.InvalidOperationException e)
                {
                    //   // ErrorLog.GetInstance().Write(e.Message);
                    throw new Exception(e.Message);
                }


                using (Stream responseStream = ftpResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        string line = reader.ReadLine();
                        while (line != null)
                        {
                            fileInfo.Add(line);
                            line = reader.ReadLine();
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                // // ErrorLog.GetInstance().Write(exp.Message);
                throw new Exception(exp.Message);
            }

            return fileInfo;

        }

        /// 
        /// 上传图片
        /// 
        /// 
        /// 
        /// 
        public bool Upload(MemoryStream mstr, string ftpUri)
        {
            try
            {
                FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUri);
                ftp.Credentials = new NetworkCredential(ftpName, ftpPwd);
                ftp.Method = WebRequestMethods.Ftp.UploadFile;
                ftp.UseBinary = true;
                ftp.UsePassive = true;
                using (Stream stream = ftp.GetRequestStream())
                {
                    byte[] bytes = mstr.ToArray();
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();
                    mstr.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                //  // ErrorLog.GetInstance("图片上传问题0711").Write("Upload:" + ex.Message + ex.StackTrace);
                //  // ErrorLog.GetInstance().Write(ex.Message);
                return false;
            }
        }

        public bool Upload(byte[] mstr, string ftpUri)
        {
            try
            {
                FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUri);
                ftp.Credentials = new NetworkCredential(ftpName, ftpPwd);
                ftp.Method = WebRequestMethods.Ftp.UploadFile;
                ftp.UseBinary = true;
                ftp.UsePassive = true;
                using (Stream stream = ftp.GetRequestStream())
                {
                    stream.Write(mstr, 0, mstr.Length);
                    stream.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                // // ErrorLog.GetInstance().Write($"上传文件时异常!ftpUri:{ftpUri},StackTrace:{ex.StackTrace},Message:{ex.Message}");
                return false;
            }
        }

        /// 
        /// 重命名文件
        /// 
        /// 文件名
        public bool RenameFileName(string fileName, string reNameFileName)
        {
            bool result = true;
            FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(reNameFileName);
            ftp.Credentials = new NetworkCredential(ftpName, ftpPwd);
            try
            {
                ftp.Method = WebRequestMethods.Ftp.Rename;
                ftp.RenameTo = fileName;
                ftp.UseBinary = true;
                ftp.UsePassive = true;
                ftpResponse = (FtpWebResponse)ftp.GetResponse();
                Stream ftpStream = ftpResponse.GetResponseStream();
                ftpStream.Close();
                ftpResponse.Close();

            }
            catch (Exception exp)
            {
                result = false;
                //   // ErrorLog.GetInstance().Write(exp.Message);
            }

            return result;
        }

        /// 
        /// 删除文件
        /// 
        /// 文件名
        public bool DeleteFile(string fileName)
        {
            bool result = true;
            FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(fileName);
            ftp.Credentials = new NetworkCredential(ftpName, ftpPwd);
            try
            {
                ftp.Method = WebRequestMethods.Ftp.DeleteFile;
                ftp.UseBinary = true;
                ftp.UsePassive = true;
                ftpResponse = (FtpWebResponse)ftp.GetResponse();
                Stream ftpStream = ftpResponse.GetResponseStream();
                ftpStream.Close();
                ftpResponse.Close();

            }
            catch (Exception exp)
            {
                result = false;
                // ErrorLog.GetInstance().Write(exp.Message);
            }

            return result;
        }

        /// 
        /// 创建目录
        /// 
        /// 
        ///  
        public bool FtpMakeDir(string Dri)
        {
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(Dri);
            req.Credentials = new NetworkCredential(ftpName, ftpPwd);
            req.Method = WebRequestMethods.Ftp.MakeDirectory;
            try
            {
                req.UsePassive = true;
                FtpWebResponse response = (FtpWebResponse)req.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                req.Abort();
                // ErrorLog.GetInstance("图片上传问题0711").Write("FtpMakeDir失败:[" + Dri + "]" + ex.Message + ex.StackTrace);
                return false;
            }
            req.Abort();
            return true;
        }

        /// 
        /// 下载
        /// 
        /// 
        /// 
        public byte[] Download(string fileName)
        {
            byte[] buffer = null;
            FtpWebResponse response = null;
            Stream ftpStream = null;
            try
            {
                string uri = ftpUri + fileName;
                Conn(uri);
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                //ftpRequest.UsePassive = true;
                response = (FtpWebResponse)ftpRequest.GetResponse();
                ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = Convert.ToInt32(response.ContentLength);//
                buffer = new byte[bufferSize];
                int readCount = 0;//已读数量
                while (readCount < bufferSize)
                {
                    readCount += ftpStream.Read(buffer, readCount, bufferSize - readCount);
                }
                ftpStream.Close();
                response.Close();

            }
            catch (Exception ex)
            {
                // ErrorLog.GetInstance().Write(ex.Message);
            }
            finally
            {
                if (ftpStream != null)
                    ftpStream.Close();
                if (response != null)
                    response.Close();
            }
            return buffer;
        }

        /// 
        /// 获取当前目录下明细(包含文件和文件夹)
        /// 
        /// 
        public string[] GetFilesDetailList(string targetPath)
        {

            var TempftpUri = targetPath;
            string[] downloadFiles;

            try
            {

                StringBuilder result = new StringBuilder();

                Conn(TempftpUri);

                //获取 FTP 服务器上的文件的详细列表的 FTP LIST 协议方法
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;


                WebResponse response = ftpRequest.GetResponse();

                StreamReader reader = new StreamReader(response.GetResponseStream());

                string line = reader.ReadLine();
                while (line != null)
                {

                    result.Append(line);

                    result.Append("\n");

                    line = reader.ReadLine();

                }

                var startIndex = result.ToString().LastIndexOf("\n");
                if (startIndex >= 0)
                {
                    result.Remove(startIndex, 1);
                }
                else
                {
                    // ErrorLog.GetInstance("图片上传问题0711").Write("result:" + result + ",targetPath:" + targetPath);
                }
                if (string.IsNullOrEmpty(result.ToString()))
                {
                    return null;
                }

                reader.Close();

                response.Close();

                return result.ToString().Split('\n');

            }

            catch (Exception ex)
            {

                // ErrorLog.GetInstance("Upload").Write(ex.Message);
                // ErrorLog.GetInstance("Upload").Write(ex.StackTrace);
                downloadFiles = new string[] { };
                return downloadFiles;

            }

        }



        /// 
        /// 获取当前目录下所有的文件夹列表(仅文件夹)
        /// 
        /// 
        public string[] GetDirectoryList(string targetPath)
        {
            string[] drectory = GetFilesDetailList(targetPath);
            if (drectory == null)
            {
                return null;
            }
            string m = "";
            if (drectory != null & drectory.Count() > 0)
            {
                foreach (string str in drectory)
                {
                    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(56).Trim();
                        if (dir != "." && dir != "..")
                        {
                            m += dir + "\n";
                        }
                    }
                }
            }
            char[] n = new char[] { '\n' };
            return m.Split(n);
        }



        /// 
        /// 判断当前目录下指定的子目录是否存在
        /// 
        /// 服务器地址
        /// 指定的目录名
        public bool DirectoryExist(string targetPath, string RemoteDirectoryName)
        {
            try
            {
                string[] dirList = GetDirectoryList(targetPath);
                if (dirList == null)
                {
                    return false;
                }

                foreach (string str in dirList)
                {

                    if (str.Trim() == RemoteDirectoryName.Trim())
                    {

                        return true;

                    }

                }
            }
            catch (Exception ex)
            {
                // ErrorLog.GetInstance("Upload").Write(ex.StackTrace);

            }

            return false;

        }


        /// 
        /// 获取指定文件大小
        /// 
        /// 
        /// 
        public long GetFileSize(string filename)
        {
            FtpWebRequest reqFTP;
            long fileSize = 0;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri + "/" + filename));

                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;

                reqFTP.UseBinary = true;

                reqFTP.Credentials = new NetworkCredential(ftpName, ftpPwd);

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                Stream ftpStream = response.GetResponseStream();

                fileSize = response.ContentLength;



                ftpStream.Close();

                response.Close();

            }

            catch (Exception ex)
            {
                // ErrorLog.GetInstance().Write(ex.Message);
            }

            return fileSize;

        }

        /// 
        /// 获取当前目录下文件列表(仅文件)
        /// 
        /// 
        public string[] GetFileList(string mask)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUri));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpName, ftpPwd);
                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) 文件不可用(例如,未找到文件,无法访问文件)。")
                {
                    // ErrorLog.GetInstance().Write(ex.Message);
                }
                return downloadFiles;
            }
        }



        public string[] GetFileNameList(string mask)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(mask));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpName, ftpPwd);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);

                string line = reader.ReadLine();
                while (line != null)
                {
                    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) 文件不可用(例如,未找到文件,无法访问文件)。")
                {
                    // ErrorLog.GetInstance().Write(ex.Message);
                }
                return downloadFiles;
            }
        }



        public bool UploadData(byte[] mstr, string ftpUri)
        {
            try
            {
                WebClient client = new WebClient();
                client.Credentials = new NetworkCredential(this.ftpName, this.ftpPwd);
                client.UploadData(ftpUri, mstr);
                return true;
            }
            catch (Exception ex)
            {
                //  // ErrorLog.GetInstance().Write(ex.Message);
                return false;
            }
        }

        public byte[] DownloadData(string uri)
        {
            try
            {
                WebClient client = new WebClient();
                client.Credentials = new NetworkCredential(this.ftpName, this.ftpPwd);
                byte[] responseData = client.DownloadData(uri);
                return responseData;
            }
            catch (Exception exp)
            {
                //  // ErrorLog.GetInstance().Write(exp.Message);
                throw new Exception(exp.Message);
            }
        }

    }

源码下载链接 https://download.csdn.net/download/yu240956419/87712432

你可能感兴趣的:(.net,mvc,layui,html)