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

2021-04-22 05:27

阅读:702

标签:ddn   static   tostring   info   格式化   methods   list   mba   his   

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

public HttpResponseMessage AddVisitNew(HttpRequestMessage request, CustomerVisitAddNewModel model)
        {
            return CreateHttpPostResponselong>(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 )
                    {
                        //获取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
    {
        /// 
        /// 将指定字符串中的格式项替换为指定数组中相应对象的字符串表示形式。
        /// 
        /// 需要格式化的字符串。
        /// 一个对象数组,其中包含零个或多个要设置格式的对象。
        /// 
        public static string Fmt(this String format, params object[] args)
        {
            return string.Format(format, args);
        }
    }
public class FtpClient
    {
        /// 
        /// FTP 服务器的 IP 地址,例如:ftp://139.129.21.10/。
        /// 
        public string FtpAddress { get; set; }

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

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

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

        /// 
        /// 创建 System.Net.FtpWebRequest 的实例。
        /// 
        /// 
        /// 
        /// 
        /// 
        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;
        }

        /// 
        /// 返回指定路径字符串的目录信息。对 System.IO.Path.GetDirectoryName() 方法的封装。
        /// 
        /// 文件或目录的路径。
        /// 
        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;
        }

        /// 
        /// 检查远程是否存在指定文件夹目录。
        /// 
        /// 文件夹目录路径。
        /// 
        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;
        }

        /// 
        /// 创建指定文件夹目录。
        /// 
        /// 文件夹目录路径。
        /// 是否抛出异常。
        /// 
        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;
        }

        /// 
        /// 上传文件。
        /// 
        /// 需要上传的本地文件路径。
        /// 上传的远程文件路径。
        /// 是否抛出异常。
        /// 
        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)

标签:ddn   static   tostring   info   格式化   methods   list   mba   his   

原文地址:http://www.cnblogs.com/hegx/p/8027033.html


评论


亲,登录后才可以留言!