设为首页 收藏本站
查看: 782|回复: 0

ftp图片上传

[复制链接]

尚未签到

发表于 2015-5-27 10:19:10 | 显示全部楼层 |阅读模式
  ///
    /// Upload 的摘要说明
    ///
    public class Upload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string result = AppConst.StringNull;
            string _productID = context.Request.QueryString["productid"];
  HttpPostedFile MyFile = context.Request.Files["Filedata"];
            //int FileLen;
            System.IO.Stream MyStream;
            //FileLen = MyFile.ContentLength;
            //byte[] input = new byte[FileLen];
            // Initialize the stream.
            MyStream = MyFile.InputStream;
            // Read the file into the byte array.
            //MyStream.Read(input, 0, FileLen);
  try
            {
                //ProductInfo productInfo = ProductManager.GetInstance().LoadProduct(_productID);
                //if (productInfo.BasicInfo == null)
                //{
                //    //throw new BizException("该商品不存在");
                //}
                int picCount = 10001;
  double ratio;//用来保持宽、高同比例放大或缩小
  //FTP服务器用户名和密码
                string ftpUserName = "liuxu";
                string ftpPassword = "Ltx#2046";
  //图片保存路径,作为拼接图片路径用
                string originalPath = "http://www.iyunv.com/tianxiang2046/admin/ftp://192.168.1.101/ProductOriginalImage/%22;//原图保存路径
                string colorPath = "http://www.iyunv.com/tianxiang2046/admin/ftp://192.168.1.101/ProductColorImage/%22;//色图
                string smallPath = "http://www.iyunv.com/tianxiang2046/admin/ftp://192.168.1.101/ProductSmallImage/%22;//小图
                string mediumPath = "http://www.iyunv.com/tianxiang2046/admin/ftp://192.168.1.101/ProductImage/%22;//中图
                string bigPath = "http://www.iyunv.com/tianxiang2046/admin/ftp://192.168.1.101/ProductBigImage/%22;//大图
  //图片地址全名包括路径
                string original1 = AppConst.StringNull;//原图保存路径
                string color1 = AppConst.StringNull;//色图
                string small1 = AppConst.StringNull;//小图
                string medium1 = AppConst.StringNull;//中图
                string big1 = AppConst.StringNull;//大图
  //图片不同尺寸大小:原图、色图、小图、中图、大图
                int colorsizeH = 30;
                int colorsizeW = 30;
                int smallsizeH = 60;
                int smallsizeW = 60;
                int mediumsizeH = 200;
                int mediumsizeW = 200;
                int bigsizeH = 1000;
                int bigsizeW = 1000;
  //拼接图片路径
                if (picCount == 0)
                {
                    original1 = originalPath + _productID + ".jpg";
                    color1 = colorPath + _productID + ".jpg";
                    small1 = smallPath + _productID + ".jpg";
                    medium1 = mediumPath + _productID + ".jpg";
                    big1 = bigPath + _productID + ".jpg";
                }
                else
                {
                    original1 = originalPath + picCount.ToString() + "_" + _productID + ".jpg";
                    color1 = colorPath + picCount.ToString() + "_" + _productID + ".jpg";
                    small1 = smallPath + picCount.ToString() + "_" + _productID + ".jpg";
                    medium1 = mediumPath + picCount.ToString() + "_" + _productID + ".jpg";
                    big1 = bigPath + picCount.ToString() + "_" + _productID + ".jpg";
                }
                FTPHelper fTPHelper = new FTPHelper(originalPath, ftpUserName, ftpPassword);
  //判断上传控件中有没有图片)
                System.Drawing.Image original = System.Drawing.Image.FromStream(MyStream);
                int originalH = original.Height;
                int originalW = original.Width;
  //设置大图的尺寸
                if (originalW > originalH)
                {
                    ratio = originalW / originalH;
                    bigsizeH = (int)(bigsizeW * ratio);
                    mediumsizeH = (int)(mediumsizeW * ratio);
                    smallsizeH = (int)(smallsizeW * ratio);
                    colorsizeH = (int)(colorsizeW * ratio);
                }
                else
                {
                    ratio = originalH / originalW;
                    bigsizeW = (int)(bigsizeH * ratio);
                    mediumsizeW = (int)(mediumsizeH * ratio);
                    smallsizeW = (int)(smallsizeH * ratio);
                    colorsizeW = (int)(colorsizeH * ratio);
                }
  //保存大尺寸图片
                System.Drawing.Image largeImage = new Bitmap(bigsizeW, bigsizeH, original.PixelFormat);
                Graphics largeGraphics = Graphics.FromImage(largeImage);
                largeGraphics.SmoothingMode = SmoothingMode.HighQuality;
                largeGraphics.CompositingQuality = CompositingQuality.HighQuality;
                largeGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle largeRectangle = new Rectangle(0, 0, bigsizeW
                    , bigsizeH);
                largeGraphics.DrawImage(original, largeRectangle);
                MemoryStream stream = new MemoryStream();
                largeImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                if (!fTPHelper.Upload(stream, big1))
                {
                    //throw "上传大图失败";
                }
  //中图
                System.Drawing.Image mediumImage = new Bitmap(mediumsizeW, mediumsizeH);
                float am = Math.Min(originalH, originalW);
                float xm = (originalW - am) / 2;
                float ym = (originalH - am) / 2;
                Graphics mediumGraphic = Graphics.FromImage(mediumImage);
                mediumGraphic.SmoothingMode = SmoothingMode.HighQuality;
                mediumGraphic.CompositingQuality = CompositingQuality.HighQuality;
                mediumGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle mediumRectangle = new Rectangle(0, 0, mediumsizeW
                    , mediumsizeH);
                mediumGraphic.DrawImage(original, mediumRectangle, xm, ym, am, am, GraphicsUnit.Pixel);
                stream = new MemoryStream();
                mediumImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                if (!fTPHelper.Upload(stream, medium1))
                {
                    //throw new BizException("上传中图失败");
                }
  //小图
                System.Drawing.Image smallImage = new Bitmap(smallsizeW, smallsizeH);
                float a = Math.Min(originalH, originalW);
                float x = (originalW - a) / 2;
                float y = (originalH - a) / 2;
                Graphics smallGraphic = Graphics.FromImage(smallImage);
                smallGraphic.SmoothingMode = SmoothingMode.HighQuality;
                smallGraphic.CompositingQuality = CompositingQuality.HighQuality;
                smallGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle smallRectangle = new Rectangle(0, 0, smallsizeW
                    , smallsizeH);
                smallGraphic.DrawImage(original, smallRectangle, x, y, a, a, GraphicsUnit.Pixel);
                stream = new MemoryStream();
                smallImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                if (!fTPHelper.Upload(stream, small1))
                {
                    //throw new BizException("上传小图失败");
                }
  //色图
                System.Drawing.Image colorImage = new Bitmap(colorsizeW, colorsizeH);
                a = Math.Min(originalH, originalW);
                x = (originalW - a) / 2;
                y = (originalH - a) / 2;
                Graphics colorGraphic = Graphics.FromImage(colorImage);
                colorGraphic.SmoothingMode = SmoothingMode.HighQuality;
                colorGraphic.CompositingQuality = CompositingQuality.HighQuality;
                colorGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle colorRectangle = new Rectangle(0, 0, colorsizeW
                    , colorsizeH);
                colorGraphic.DrawImage(original, colorRectangle, x, y, a, a, GraphicsUnit.Pixel);
                stream = new MemoryStream();
                colorImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                if (!fTPHelper.Upload(stream, color1))
                {
                    //throw new BizException("上传色图失败");
                }
  //原图
                System.Drawing.Image originalImage = new Bitmap(originalW, originalH);
                a = Math.Min(originalH, originalW);
                x = (originalW - a) / 2;
                y = (originalH - a) / 2;
                Graphics originalGraphic = Graphics.FromImage(originalImage);
                originalGraphic.SmoothingMode = SmoothingMode.HighQuality;
                originalGraphic.CompositingQuality = CompositingQuality.HighQuality;
                originalGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle originalRectangle = new Rectangle(0, 0, originalW
                    , originalH);
                originalGraphic.DrawImage(original, originalRectangle, x, y, a, a, GraphicsUnit.Pixel);
                stream = new MemoryStream();
                originalImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                if (!fTPHelper.Upload(stream, original1))
                {
                    //throw new BizException("上传原图失败");
                }
  //释放资源
                largeImage.Dispose();
                largeGraphics.Dispose();
                mediumImage.Dispose();
                mediumGraphic.Dispose();
                smallImage.Dispose();
                smallGraphic.Dispose();
                original.Dispose();
  //productInfo.BasicInfo.MultiPicNum++;
                //ProductManager.GetInstance().UpdateBasicInfo(productInfo.BasicInfo);
  StringBuilder str2 = new StringBuilder();
                //ProductInfo productInfo2 = Icson.BLL.Basic.ProductManager.GetInstance().LoadProduct(_productID);
                //for (int i = 1; i  0)
                            {
                                outputStream.Write(buffer, 0, readCount);
                                readCount = ftpStream.Read(buffer, 0, bufferSize);
                            }
                        }
                        msg = ftpResponse.StatusDescription;
                    }
                }
            }
            catch (Exception exp)
            {
                msg = "Failed to download:" + exp.Message;
                throw new BizException(exp.Message);
            }
        }
  ///
        /// 文件下载,使用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)
            {
  throw new BizException(exp.Message);
            }
        }
  ///
        /// 遍历文件
        ///
        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 BizException(e.Message);
                }
                catch (System.InvalidOperationException e)
                {
                    ErrorLog.GetInstance().Write(e.Message);
                    throw new BizException(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 BizException(exp.Message);
            }
  return fileInfo;
  }
  ///
        /// 上传图片
        ///
        ///
        ///
        ///
        public bool Upload(MemoryStream mstr, string ftpUri)
        {
            try
            {
                FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUri);
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.credentials/ = new NetworkCredential(ftpName, ftpPwd);
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.method/ = WebRequestMethods.Ftp.UploadFile;
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.usebinary/ = true;
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.usepassive/ = true;
                using (Stream stream = http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.getrequeststream/())
                {
                    byte[] bytes = mstr.ToArray();
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();
                    mstr.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
  public bool Upload(byte[] mstr, string ftpUri)
        {
            try
            {
                FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUri);
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.credentials/ = new NetworkCredential(ftpName, ftpPwd);
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.method/ = WebRequestMethods.Ftp.UploadFile;
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.usebinary/ = true;
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.usepassive/ = true;
                using (Stream stream = http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.getrequeststream/())
                {
                    stream.Write(mstr, 0, mstr.Length);
                    stream.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
  ///
        /// 重命名文件
        ///
        /// 文件名
        public bool RenameFileName(string fileName, string reNameFileName)
        {
            bool result = true;
            FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(reNameFileName);
            http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.credentials/ = new NetworkCredential(ftpName, ftpPwd);
            try
            {
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.method/ = WebRequestMethods.Ftp.Rename;
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.renameto/ = fileName;
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.usebinary/ = true;
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.usepassive/ = true;
                ftpResponse = (FtpWebResponse)ftp.GetResponse();
                Stream ftpStream = ftpResponse.GetResponseStream();
                ftpStream.Close();
                ftpResponse.Close();
  }
            catch (Exception exp)
            {
                result = false;
            }
  return result;
        }
  ///
        /// 删除文件
        ///
        /// 文件名
        public bool DeleteFile(string fileName)
        {
            bool result = true;
            FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(fileName);
            http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.credentials/ = new NetworkCredential(ftpName, ftpPwd);
            try
            {
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.method/ = WebRequestMethods.Ftp.DeleteFile;
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.usebinary/ = true;
                http://www.iyunv.com/tianxiang2046/admin/ftp://ftp.usepassive/ = true;
                ftpResponse = (FtpWebResponse)ftp.GetResponse();
                Stream ftpStream = ftpResponse.GetResponseStream();
                ftpStream.Close();
                ftpResponse.Close();
  }
            catch (Exception exp)
            {
                result = false;
            }
  return result;
        }
  ///
        /// Summary description for BizException.
        ///
        [Serializable]
        public class BizException : ApplicationException
        {
            private string MsgCn;
            private string MsgEn;
            public BizException() { }
  public BizException(string message)
                : base(message)
            {
                MsgCn = message;
            }
  public BizException(string messageCn, string messageEn)
                : base(messageCn)
            {
  MsgCn = messageCn;
                MsgEn = messageEn;
            }
  
  //public BizException(string message, Exception e) : base(message, e) {}
        }
  }
  -----------------------------------------------------------
  
  public class ErrorLog
    {
        private static object locker = new object();
  private ErrorLog()
        {
        }
  private static ErrorLog log = new ErrorLog();
  
        ///
        /// 返回日志实例
        ///
        ///
        public static ErrorLog GetInstance()
        {
            lock (locker)
            {
                if ("c:\\Temp\\IcsonError\\" != null)
                {
                    errorLogFolder = "c:\\Temp\\IcsonError\\";
  try
                    {
                        if (!Directory.Exists(errorLogFolder))
                            Directory.CreateDirectory(errorLogFolder);
                    }
                    catch (Exception exp)
                    {
                        Console.Write(exp.ToString());
                    }
                }
  string str = DateTime.Now.ToString("yyyy-MM-dd");
                errorLogFile = errorLogFolder + str + ".txt";
  try
                {
                    if (File.Exists(errorLogFile) == false)
                    {
                        FileStream stream = File.Create(errorLogFile);
                        stream.Close();
                    }
                }
                catch (Exception exp)
                {
                    Console.Write(exp.ToString());
                }
            }
  return log;
        }
  ///
        /// write log to file
        ///
        ///
        public void Write(string message)
        {
            lock (locker)
            {
                StreamWriter writer = null;
                try
                {
                    writer = new StreamWriter(errorLogFile, true, System.Text.Encoding.Default);
                    StringBuilder sb = new StringBuilder(500);
                    sb.Append(DateTime.Now.ToString()).Append(DateTime.Now.Ticks.ToString()).Append("\r\n");
                    sb.Append(message).Append("\r\n");
                    sb.Append("---------------------------------------").Append("\r\n");
                    writer.Write(sb.ToString());
                }
                catch (IOException ioe)
                {
                    Console.WriteLine(ioe.ToString());
                }
                finally
                {
                    try
                    {
                        if (writer != null)
                            writer.Close();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
            }
        }
  private static string errorLogFolder = @"c:\Temp\IPP3Log\";
        private static string errorLogFile;
  }
  
  
  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-71152-1-1.html 上篇帖子: 【7月19日】FTP共享 下篇帖子: 全国大学FTP站列表
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表