Пример #1
0
        public static FileUploader ReceiveImg(byte[] bytes)
        {
            bool image        = true;
            var  filename     = "";
            var  filetransfer = false;

            try
            {
                DateTime now = DateTime.Now.Date;

                string currentType = "";

                #region 图片需要特殊处理
                if (image)//判断是否为图片
                {
                    #region 加载成图片,并可图片进行缩放处理
                    try
                    {
                        using (var ms = new System.IO.MemoryStream(bytes, 0, bytes.Length)) //二进制
                            using (var sImage = System.Drawing.Image.FromStream(ms))
                            {
                                ImageFormat format = sImage.RawFormat;//

                                if (format.Equals(ImageFormat.Jpeg))
                                {
                                    currentType = ".jpg";
                                }
                                if (format.Equals(ImageFormat.Png))
                                {
                                    currentType = ".png";
                                }
                                if (format.Equals(ImageFormat.Bmp))
                                {
                                    currentType = ".bmp";
                                }
                                if (format.Equals(ImageFormat.Gif))
                                {
                                    currentType = ".gif";
                                }
                            }
                    }
                    catch
                    {
                        return(new FileUploader()
                        {
                            Success = false, Message = "文件类型不符合要求。"
                        });
                    }
                    #endregion
                }
                #endregion

                var t = "";
                if (string.IsNullOrEmpty(filename))
                {
                    string locator = "/" + "upload" + "/" + (image ? "images" : "files") + "/" + now.Year + "/" + now.Month.ToString("00") + "/" + now.Day.ToString("00") + "/";
                    filename = (locator + DateTime.Now.ToString("HHmmssfff") + currentType);

                    if (!image && currentType.ToLower() == ".pdf")//如果是pdf,单独上传一个
                    {
                        locator  = "/" + "upload" + "/pdf/" + now.Year + "/" + now.Month.ToString("00") + "/" + now.Day.ToString("00") + "/";
                        filename = (locator + DateTime.Now.ToString("HHmmssfff") + currentType);
                    }
                }
                else
                {
                    filename = System.Web.HttpUtility.UrlDecode(filename, Encoding.UTF8);
                }

                var success = SaveAs(filename, bytes);

                if (success && !filetransfer)//设置一个标志,为了防止重复调用
                {
                    string[] transfers = (System.Configuration.ConfigurationManager.AppSettings["FileUploader.Transfer"] ?? "").Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var transfer in transfers)
                    {
                        if (!string.IsNullOrEmpty(transfer))
                        {
                            FileUploader.Transfer(transfer + "?action=uploadimage", bytes, filename);
                        }
                    }
                }

                var server = System.Configuration.ConfigurationManager.AppSettings["FileUploader.Locator"];
                if (string.IsNullOrWhiteSpace(server))
                {
                    server = "/";
                }
                //locator = locator.TrimEnd("/");
                return(new FileUploader()
                {
                    Success = success, Message = "", Locator = server.TrimEnd('/') + "/" + filename.TrimStart('/'), Original = "", FileType = currentType
                });
            }
            catch (Exception ex)
            {
                return(new FileUploader()
                {
                    Success = false, Message = ex.Message.ToString()
                });
            }
        }
Пример #2
0
        /// <summary>
        /// 保存文件到本地
        /// </summary>
        /// <param name="files"></param>
        /// <param name="pathbase"></param>
        /// <param name="filetype"></param>
        /// <param name="size"></param>
        /// <param name="onProcess"></param>
        /// <returns></returns>
        public static FileUploader Receive(string action = "uploadimage", int filesize = 500, string fileexts = null, int[] imgzoom = null)
        {
            bool image = action.ToLower() == "uploadimage";

            //如果数据是转过来的
            var filename     = WebHelper.Form("filename");
            var files        = System.Web.HttpContext.Current.Request.Files;
            var filetransfer = WebHelper.Form("filetransfer").ToLower() == "true";

            //默认为50M
            filesize = filesize < 0 ? 50 * 1024 : filesize;
            filesize = filesize > 50 * 1024 ? 50 * 1024 : filesize;

            #region 文件格式处理
            HashSet <string> allowtypes = new HashSet <string>()
            {
                ".rar", ".zip", ".doc", ".docx", ".pdf", ".txt", ".swf", ".xls", ".xlsx"
            };
            if (image)
            {
                allowtypes = new HashSet <string>()
                {
                    ".gif", ".png", ".jpg", ".jpeg", ".bmp"
                };
                filesize = filesize < 0 ? 1024 : filesize;
                filesize = filesize > 1024 ? 1024 : filesize;
            }
            if (!string.IsNullOrEmpty(fileexts) && fileexts != "" && fileexts.StartsWith("."))
            {
                string[]         splits = fileexts.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                HashSet <string> types  = new HashSet <string>();
                foreach (var s in splits)
                {
                    if (allowtypes.Contains(s))
                    {
                        types.Add(s);
                    }
                }
                allowtypes.Clear();
                allowtypes = types;
            }
            #endregion

            #region 文件检查
            if (files == null || files.Count == 0 || files[0].InputStream == null || files[0].InputStream.Length == 0)
            {
                return(new FileUploader()
                {
                    Success = false, Message = "未找到有效的上传文件!"
                });
            }
            string currentType = FileUploader.GetFileExt(files[0].FileName); //获取文件扩展名

            if (!allowtypes.Contains(currentType))                           //检查当前文件格式是否符合要求
            {
                return(new FileUploader()
                {
                    Success = false, Message = "文件类型不符合要求。"
                });
            }

            if (filesize > 0 && files[0].ContentLength >= (filesize * 1024))//检查文件大小
            {
                return(new FileUploader()
                {
                    Success = false, Message = "文件大小不符合要求。"
                });
            }
            #endregion

            try
            {
                var      uploadFile   = files[0];            //获取当前文件
                string   originalName = uploadFile.FileName; //获取当前的文件名
                DateTime now          = DateTime.Now.Date;

                //保存的路径

                byte[] bytes = new byte[uploadFile.ContentLength];

                using (System.IO.Stream fs = (System.IO.Stream)uploadFile.InputStream)
                {
                    fs.Read(bytes, 0, uploadFile.ContentLength);
                    fs.Close();
                }

                int w = 0;
                int h = 0;

                #region 图片需要特殊处理
                if (image)//判断是否为图片
                {
                    #region 加载成图片,并可图片进行缩放处理
                    try
                    {
                        using (var ms = new System.IO.MemoryStream(bytes, 0, bytes.Length)) //二进制
                            using (var sImage = System.Drawing.Image.FromStream(ms))
                            {
                                w = sImage.Width;
                                h = sImage.Height;
                                ImageFormat format = sImage.RawFormat;//

                                if (format.Equals(ImageFormat.Jpeg))
                                {
                                    currentType = ".jpg";
                                }
                                if (format.Equals(ImageFormat.Png))
                                {
                                    currentType = ".png";
                                }
                                if (format.Equals(ImageFormat.Bmp))
                                {
                                    currentType = ".bmp";
                                }
                                if (format.Equals(ImageFormat.Gif))
                                {
                                    currentType = ".gif";
                                }

                                //如果需要进行处理,则进行相应的操作
                                if (imgzoom.Length > 0 && (imgzoom[0] > 0 || imgzoom[1] > 0))
                                {
                                    if (!Photos.Zoom(ref bytes, sImage.Width, sImage.Height, imgzoom[0], imgzoom[1], ref currentType))
                                    {
                                        //文件缩放失败
                                    }
                                }



                                if (!allowtypes.Contains(currentType))//检查当前文件格式是否符合要求
                                {
                                    return(new FileUploader()
                                    {
                                        Success = false, Message = "文件类型不符合要求"
                                    });
                                }
                            }
                    }
                    catch
                    {
                        return(new FileUploader()
                        {
                            Success = false, Message = "文件类型不符合要求。"
                        });
                    }
                    #endregion
                }
                #endregion

                var t = "";
                if (string.IsNullOrEmpty(filename))
                {
                    string locator = "/" + "upload" + "/" + (image ? "images" : "files") + "/" + now.Year + "/" + now.Month.ToString("00") + "/" + now.Day.ToString("00") + "/";
                    filename = (locator + DateTime.Now.ToString("HHmmssfff") + currentType);

                    if (!image && currentType.ToLower() == ".pdf")//如果是pdf,单独上传一个
                    {
                        locator  = "/" + "upload" + "/pdf/" + now.Year + "/" + now.Month.ToString("00") + "/" + now.Day.ToString("00") + "/";
                        filename = (locator + DateTime.Now.ToString("HHmmssfff") + currentType);
                    }
                }
                else
                {
                    filename = System.Web.HttpUtility.UrlDecode(filename, Encoding.UTF8);
                }

                var success = SaveAs(filename, bytes);

                if (success && !filetransfer)//设置一个标志,为了防止重复调用
                {
                    string[] transfers = (System.Configuration.ConfigurationManager.AppSettings["FileUploader.Transfer"] ?? "").Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var transfer in transfers)
                    {
                        if (!string.IsNullOrEmpty(transfer))
                        {
                            FileUploader.Transfer(transfer + "?action=" + action, bytes, filename);
                        }
                    }
                }

                var server = System.Configuration.ConfigurationManager.AppSettings["FileUploader.Locator"];
                if (string.IsNullOrWhiteSpace(server))
                {
                    server = "/";
                }
                //locator = locator.TrimEnd("/");
                return(new FileUploader()
                {
                    Width = w, Height = h, Success = success, Message = "", Locator = server.TrimEnd('/') + "/" + filename.TrimStart('/'), Original = originalName, FileType = currentType
                });
            }
            catch (Exception ex)
            {
                return(new FileUploader()
                {
                    Success = false, Message = ex.Message.ToString()
                });
            }
        }