webapi批量上传照片到ftp服务器(base64)

Posted 何光曦

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了webapi批量上传照片到ftp服务器(base64)相关的知识,希望对你有一定的参考价值。

一段demo。做的时候根据自己的需求改造下

public HttpResponseMessage AddVisitNew(HttpRequestMessage request, CustomerVisitAddNewModel model)
        {
            return CreateHttpPostResponse<long>(request, () =>
            {
                var res = customerVisitInfoService.AddVisitNew(model, CurrentUserId);
                if (string.IsNullOrEmpty(res.Error))
                {
                    // 上传拜访记录照片
                    string visitPath = null;
                    FtpClient ftpClient = new FtpClient(GlobalConst.FtpAddress, GlobalConst.Username, GlobalConst.Password);
                    string visitUploadDir = Path.Combine(GlobalConst.FILE_VISIT, "file");

                    for (var i = 0; i < model.VisitPic.Count; i++)
                    {
                        //获取base64编码的图片
                        HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];

                        //获取文件储存路径
                        string path = context.Request.MapPath("~/"); //获取当前项目所在目录
                        string fName = "{0}".Fmt(DateTime.Now.ToString("yyyyMMddHHmmssfff")) + i;
                        string suffix = ".jpg"; 
                        string strPath = path + "App_Data/" + fName + suffix;
                        string newFileName = fName + suffix;

                        //获取图片并保存
                        Base64ToImg(model.VisitPic[i].Split(,)[1]).Save(strPath);
                        
                        //上传FTP
                        string uploadFilePath = Path.Combine(visitUploadDir, newFileName);
                        visitPath = ftpClient.UploadFile(strPath, uploadFilePath, true);
                        //FTP 转 HTTP
                        visitPath = "{0}".Fmt(UriHelper.GetAbsolutePath(visitPath));
                        
                        var pic = new VisitPiction
                        {
                            CustomerVisitInfoId = res.Data,
                            Createtime = DateTime.Now,
                            Path = visitPath
                        };
                        customerVisitInfoService.AddVisitPic(pic);
                    }
                    Logger.Info("visits/add customer: " + model.CustomerId + ", VisitStatus: " + model.VisitStatus + ", ReVisitPlanTime: " + model.ReVisitPlanTime + ", ExpenrienceTime: " + model.ExpenrienceTime);
                }
                return res;
            });
        }

        //解析base64编码获取图片
        private Bitmap Base64ToImg(string base64Code)
        {
            MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Code));
            return new Bitmap(stream);
        }
public static class StringExtensions
    {
        /// <summary>
        /// 将指定字符串中的格式项替换为指定数组中相应对象的字符串表示形式。
        /// </summary>
        /// <param name="format">需要格式化的字符串。</param>
        /// <param name="args">一个对象数组,其中包含零个或多个要设置格式的对象。</param>
        /// <returns></returns>
        public static string Fmt(this String format, params object[] args)
        {
            return string.Format(format, args);
        }
    }
public class FtpClient
    {
        /// <summary>
        /// FTP 服务器的 IP 地址,例如:ftp://139.129.21.10/。
        /// </summary>
        public string FtpAddress { get; set; }

        /// <summary>
        /// FTP 服务器通讯的用户名。
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// FTP 服务器通讯的密码。
        /// </summary>
        public string Password { get; set; }

        public FtpClient(string ftpAddress, string userName, string password)
        {
            this.FtpAddress = ftpAddress;
            this.UserName = userName;
            this.Password = password;
        }

        /// <summary>
        /// 创建 System.Net.FtpWebRequest 的实例。
        /// </summary>
        /// <param name="path"></param>
        /// <param name="method"></param>
        /// <param name="keepAlive"></param>
        /// <returns></returns>
        private FtpWebRequest CreateRequest(string path, string method = WebRequestMethods.Ftp.DownloadFile,
            bool keepAlive = false)
        {
            if (!Path.HasExtension(path))
                path = !(path.EndsWith("/") || path.EndsWith("\\")) ? "{0}/".Fmt(path) : path;
            string uriString = Path.Combine(FtpAddress, path.Replace("\\", "/"));
            Uri requestUri = new Uri(uriString);
            FtpWebRequest result = (FtpWebRequest)WebRequest.Create(requestUri);
            result.Method = method;
            result.KeepAlive = keepAlive;
            //result.UsePassive = usePassive;
            result.Credentials = new NetworkCredential(UserName, Password);
            return result;
        }

        /// <summary>
        /// 返回指定路径字符串的目录信息。对 System.IO.Path.GetDirectoryName() 方法的封装。
        /// </summary>
        /// <param name="path">文件或目录的路径。</param>
        /// <returns></returns>
        public static string GetDirectoryName(string path)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(path))
            {
                if (!string.IsNullOrEmpty(Path.GetExtension(path)))
                    result = Path.GetDirectoryName(path);
                else
                    result = !(path.EndsWith("/") || path.EndsWith("\\")) ? "{0}/".Fmt(path) : path;
            }
            return result;
        }

        /// <summary>
        /// 检查远程是否存在指定文件夹目录。
        /// </summary>
        /// <param name="directory">文件夹目录路径。</param>
        /// <returns></returns>
        public bool IsDirectoryExist(string directory)
        {
            var result = true;
            try
            {
                directory = FtpClient.GetDirectoryName(directory);
                 var ftpWebRequest = this.CreateRequest(directory, WebRequestMethods.Ftp.ListDirectory);
                using (var ftpWebResponse = ftpWebRequest.GetResponse()) { }
            }
            catch
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 创建指定文件夹目录。
        /// </summary>
        /// <param name="directory">文件夹目录路径。</param>
        /// <param name="isThrowEx">是否抛出异常。</param>
        /// <returns></returns>
        public bool CreateDirectory(string directory, bool isThrowEx = false)
        {
            var result = false;
            try
            {
                //一级一级创建文件夹目录
                directory = FtpClient.GetDirectoryName(directory);
                string[] directorys = directory.Split(/, \\);
                string path = string.Empty; //上级目录
                foreach (var dir in directorys)
                {
                    path = "{0}{1}/".Fmt(path, dir);
                    if (!IsDirectoryExist(dir))
                    {
                        var ftpWebRequest = this.CreateRequest(path, WebRequestMethods.Ftp.MakeDirectory);
                        using (var ftpWebResponse = ftpWebRequest.GetResponse()) { }
                    }
                    result = true;
                }
            }
            catch (Exception ex)
            {
                if (isThrowEx) throw ex;
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 上传文件。
        /// </summary>
        /// <param name="loclFilePath">需要上传的本地文件路径。</param>
        /// <param name="remoteFilePath">上传的远程文件路径。</param>
        /// <param name="isThrowEx">是否抛出异常。</param>
        /// <returns></returns>
        public string UploadFile(string loclFilePath, string remoteFilePath, bool isThrowEx = false)
        {
            string result = string.Empty;
            try
            {
                if (!IsDirectoryExist(remoteFilePath))
                    CreateDirectory(remoteFilePath, true);
                FileInfo fileInfo = new FileInfo(loclFilePath);
                var ftpWebRequest = this.CreateRequest(remoteFilePath, WebRequestMethods.Ftp.UploadFile);
                ftpWebRequest.ContentLength = fileInfo.Length;
                //将文件流写入请求流中
                using (var fileStream = fileInfo.OpenRead())
                {
                    using (var requestStream = ftpWebRequest.GetRequestStream())
                    {
                        int bufferLength = 2048;
                        byte[] buffer = new byte[bufferLength];
                        int readLength = 0;
                        while ((readLength = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            requestStream.Write(buffer, 0, readLength);
                        }
                    }
                }
                result = ftpWebRequest.RequestUri.AbsoluteUri;
            }
            catch (Exception ex)
            {
                if (isThrowEx) throw ex;
            }
            return result;
        }
    }

 


以上是关于webapi批量上传照片到ftp服务器(base64)的主要内容,如果未能解决你的问题,请参考以下文章

C# winform如何实现批量上传文件到远程服务器?

批量文件将目录中的所有文件上传到FTP

批量ftp上传工具,推荐3款免费的ftp服务器软件,批量ftp上传工具

使用 bash 脚本批量重命名 FTP 服务器上的文件

指定间隔定时拍照抓拍摄像头(机)FTP上传照片|内存卡存储 [WiFi/4G传输][太阳能电池供电方案]

linux FTP批量上传下载文件