191145686 发表于 2015-5-27 10:19:10

ftp图片上传

  ///
    /// 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;
            // 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; i0)
                            {
                              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.
      ///
      
      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]
查看完整版本: ftp图片上传