图片上传帮助类

 /// <summary>
    /// UploadLocalImages 的摘要说明
    /// </summary>
    public class UploadLocalImages : IHttpHandler
    {

        public static string baseFileUrl = "~/UploadImg/Temp/";
        /// <summary>
        /// 文件上传处理  lh
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            result rs = new result();
            rs.status = 0;
            rs.url = new List<string>();
            rs.imgDatas = new List<byte[]>();
            try
            {
                string action = context.Request.Form["action"];
                switch (action)
                {
                    case "local"://上传至网站保存
                        SaveToLocal(context, ref rs);
                        break;
                }
            }
            catch (Exception ex)
            {
                rs.status = 0;
                rs.msg = ex.Message;
                if (rs.url.Count > 0)
                {
                    System.Threading.Thread t = new System.Threading.Thread(DeleFile);
                    t.Start(rs.url);
                }
            }
            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(rs));
        }

        /// <summary>
        /// 保存至网站
        /// </summary>
        /// <param name="context"></param>
        /// <param name="json"></param>
        private void SaveToLocal(HttpContext context, ref result result)
        {
            if (context.Request.Files.Count == 0)
            {
                result.status = 0;
                result.msg = "请选择一张图片";
                return;
            }
            //文件基路径
            string baseUrl = context.Request.Form["baseUrl"];
            string SaveImageAddress = context.Server.MapPath(baseFileUrl);
            //int Width = 0;
            //int Height = 0;
            //int.TryParse(context.Request["Width"], out Width);//指定宽
            //int.TryParse(context.Request["Height"], out Height);//指定高
            bool isNotImage = context.Request.Form["isNotImage"] == "1";//是否非图片
            //bool isTemp = context.Request.Form["isTemp"] == "1";//是否转变二进制
            int maxLen = 1024 * 500;//大小限制,单位为字节
            if (!string.IsNullOrWhiteSpace(context.Request.Form["maxLen"]))
                maxLen = Convert.ToInt32(context.Request.Form["maxLen"]);
            List<HttpPostedFile> files = ToHttpPostedFileList(context.Request.Files);
            if (files.Count > 0)
            {
                if (!isNotImage && !isImage(files))
                {
                    result.status = 0;
                    result.msg = "上传格式不正确,请上传gif,jpg,jpeg,png,bmp格式的图片";
                }
                foreach (HttpPostedFile file in files)
                {
                    if (file.InputStream.Length > maxLen)
                    {
                        result r = new result()
                        {
                            status = 0,
                            msg = "图片不能大于500K"
                        };
                        return;
                    }
                    //System.Drawing.Image originalImage = System.Drawing.Image.FromStream(file.InputStream);
                    //if (Width <= 0)
                    //{
                    //    Width = originalImage.Width;
                    //}
                    //if (Height <= 0)
                    //{
                    //    Height = originalImage.Height;
                    //}
                    //System.Drawing.Image bitmap = new System.Drawing.Bitmap(Width, Height);
                    //System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
                    //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
                    //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
                    //g.Clear(System.Drawing.Color.Transparent);
                    //g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, Width, Height),
                    //    new System.Drawing.Rectangle(0, 0, originalImage.Width, originalImage.Height),
                    //    System.Drawing.GraphicsUnit.Pixel);
                    if (!Directory.Exists(SaveImageAddress))
                    {
                        Directory.CreateDirectory(SaveImageAddress);
                    }
                    file.SaveAs(SaveImageAddress + baseUrl);
                    //bitmap.Save(SaveImageAddress + "/" + file.FileName);
                    //if (isTemp)
                    //{
                    //    result.imgDatas.Add(GetFileData(SaveImageAddress + "/" + file.FileName));
                    //    DeleFile((baseUrl + "/" + file.FileName).ToList());
                    //}
                    //else
                    //    result.url.Add(baseUrl + "/" + file.FileName);
                }
                result.status = 1;
                result.msg = "上传成功";
            }
            else
            {
                result.status = 0;
                result.msg = "请选择具体文件上传";
            }
        }
        /// <summary>
        /// 图片转换二进制流
        /// </summary>
        public static byte[] GetFileData(string imagepath)
        {
            根据文件的路径使用文件流打开,并保存为byte[] 
            if (!File.Exists(imagepath))
                return null;
            FileStream fs = new FileStream(imagepath, FileMode.Open);
            byte[] byData = new byte[fs.Length];
            fs.Read(byData, 0, byData.Length);
            fs.Close();
            return byData;
        }

        /// <summary>
        /// 验证是否是图片格式
        /// </summary>
        /// <param name="expends"></param>
        /// <returns></returns>
        public bool isImage(List<HttpPostedFile> files)
        {
            bool rs = true;
            List<string> listString = ".gif,.jpg,.jpeg,.png,.bmp".Split(',').ToList();
            foreach (HttpPostedFile item in files)
            {
                string type = item.FileName.ToLower().Substring(item.FileName.LastIndexOf('.'));
                if (!listString.Contains(type))
                {
                    rs = false;
                    break;
                }
            }
            return rs;
        }
        public class result
        {
            public int status { get; set; }
            public string msg { get; set; }
            public List<byte[]> imgDatas { get; set; }
            public List<string> url { get; set; }
        }

        /// <summary>
        /// 获取上载文件集合
        /// </summary>
        public static List<HttpPostedFile> ToHttpPostedFileList(HttpFileCollection collection)
        {
            List<HttpPostedFile> list = new List<HttpPostedFile>();
            if (collection != null)
            {
                for (int i = 0; i < collection.Count; i++)
                    list.Add(collection[i]);
            }
            return list;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath">文件绝对路径</param>
        public static void DeleFile(object filePaths)
        {
            List<string> list = filePaths as List<string>;
            try
            {
                foreach (var filePath in list)
                {
                    System.IO.FileInfo DeleFile = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(filePath));
                    if (DeleFile.Exists)
                        DeleFile.Delete();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath">文件绝对路径</param>
        public static void DeleFile(string
 filePaths)
        {
            try
            {
                System.IO.FileInfo DeleFile = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(filePaths));
                if (DeleFile.Exists)
                    DeleFile.Delete();

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值