Beispiel #1
0
        public static string Upload(FileType fileType, int maxFileSize, out string[] orginalFileName, out string[] fileSize, out string[] newFileName, HttpFileCollectionBase hpfs)
        {
            var           i       = 0;
            StringBuilder builder = new StringBuilder();

            if (hpfs.Count > 0)
            {
                var rank = hpfs.Count;
                orginalFileName = new string[rank];
                fileSize        = new string[rank];
                newFileName     = new string[rank];

                for (var j = 0; j < rank; j++)
                {
                    orginalFileName[j] = fileSize[j] = newFileName[j] = string.Empty;
                }

                bool   flag       = true;
                string uploadpath = GetUploadPath(fileType);


                for (var l = 0; l < hpfs.Count; l++)
                {
                    HttpPostedFileBase hpf = hpfs[l];

                    flag = ExecUploadFile(hpf, uploadpath, fileType, maxFileSize, out orginalFileName[i], out fileSize[i], out newFileName[i]);

                    i++;
                    if (!flag && hpf.HasFile())
                    {
                        builder.AppendFormat(@"第{0}个文件上传出错:
                                            文件类型-{1};
                                            文件大小-{2}k;
                                            允许上传的文件类型:{3};
                                            允许上传的文件大小:{4}M",
                                             (i),
                                             Path.GetExtension(hpf.FileName),
                                             hpf.ContentLength / 1024,
                                             GetAllowExt(fileType),
                                             DefaultFileMaxSize / (1024 * 1024)
                                             );

                        continue;
                    }
                }
            }
            else
            {
                orginalFileName = null;
                fileSize        = null;
                newFileName     = null;
                builder.Append("没有上传文件!");
            }

            return(builder.ToString());
        }
        public static bool AllowFile(this HttpPostedFileBase file)
        {
            var allowedExtensions = new[] { ".jpg", ".png", ".gif", ".jpge" };

            if (!file.HasFile())
            {
                return(false);
            }

            var extension = Path.GetExtension(file.FileName);

            return(extension != null && allowedExtensions.Contains(extension.ToLower()) ? true : false);
        }
Beispiel #3
0
        public static string AddNewGuidNameToFileToPDF(this HttpPostedFileBase file)
        {
            if (file.HasFile())
            {
                string fileNewName = Guid.NewGuid().ToString();
                //string fileExtension = Path.GetExtension(file.FileName);
                fileNewName = string.Format("{0}{1}", fileNewName, ".pdf");

                return(fileNewName);
            }

            return("");
        }
Beispiel #4
0
 /// <summary>
 /// verifica se a imagem é jpg, gif, ou png
 /// </summary>
 /// <param name="file"></param>
 /// <returns></returns>
 public static bool CheckIfFileIsImageFormat(this HttpPostedFileBase file)
 {
     if (file.HasFile())
     {
         string fileExtension = file.FileName.Right(4);
         Regex  reg           = new Regex(@"\.(jpg|gif|png)$");
         if (reg.Match(fileExtension).Success)
         {
             return(true);
         }
     }
     return(false);
 }
Beispiel #5
0
        /// <summary>
        /// Substitui o nome do arquivo atual adicionando um numero para o documento
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string AddNewNameForDocument(this HttpPostedFileBase file)
        {
            if (file.HasFile())
            {
                Random rnd           = new Random();
                string fileNewName   = string.Format("{0}_{1}", file.FileName.Left(file.FileName.Length - 4), rnd.Next(100, 1000).ToString());
                string fileExtension = Path.GetExtension(file.FileName);
                fileNewName = string.Format("{0}{1}", fileNewName, fileExtension);

                return(fileNewName);
            }

            return("");
        }
Beispiel #6
0
        private static bool ExecUploadFile(HttpPostedFileBase hpf, string uploadPath, FileType fileType, int maxSize, out string orginalName, out string fileSize, out string newFileName)
        {
            orginalName = string.Empty;
            fileSize    = string.Empty;
            newFileName = string.Empty;

            try
            {
                if (!hpf.HasFile())
                {
                    return(true);
                }

                string fileName = Path.GetFileName(hpf.FileName);
                string fileExt  = Path.GetExtension(hpf.FileName);
                int    filesize = hpf.ContentLength;

                //检测文件类型
                if (!CheckValidFile(fileType, fileExt))
                {
                    return(false);
                }

                //检测文件大小
                if (!CheckFileSize(maxSize, filesize))
                {
                    return(false);
                }

                //CreateDirectory(path);//创建文件夹
                orginalName = fileName;                    //原始名字
                fileSize    = filesize.ToString();
                fileName    = GeneralFileName() + fileExt; //新名字
                newFileName = Path.Combine(uploadPath, fileName);
                hpf.SaveAs(newFileName);

                return(true);
            }
            catch (IOException e)
            {
                LogHelper.Error(e);
                return(false);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return(false);
            }
        }
Beispiel #7
0
        /// <summary>
        /// 上传店铺简介图片
        /// </summary>
        /// <param name="fileData"></param>
        /// <returns></returns>
        public JsonResult UploadStoreImg()
        {
            HttpPostedFileBase fileData = Request.Files[0];
            string             saveFilePath;

            if (!fileData.HasFile())
            {
                return(Json(new ImageView()
                {
                    Error = 1, Message = "上載的圖片无效!"
                }));
            }
            try
            {
                string uploadFileName = fileData.FileName;
                string imageExtension = Path.GetExtension(uploadFileName);

                if (!ValidateImageExtension(imageExtension))
                {
                    return(Json(new ImageView()
                    {
                        Error = 1, Message = "不允許上載“" + imageExtension + "”格式的圖片!"
                    }));
                }
                else
                {
                    string relativeDir = PathHelper.GetSaveSjPathImg();

                    CheckOrCreateDirectory(ConfigHelper.SharePath + relativeDir);

                    string tempStr = StringHelper.GetRandomString(12) + imageExtension;
                    saveFilePath = relativeDir + StringHelper.GetRandomString(12) + imageExtension;

                    fileData.SaveAs(ConfigHelper.SharePath + saveFilePath);
                }
            }
            catch
            {
                saveFilePath = string.Empty;
            }

            string saveFileUrl = ConfigHelper.ImageServer + saveFilePath.Replace(ConfigHelper.SharePath, "").Replace('\\', '/');
            var    image       = new ImageView {
                Path = saveFilePath.Replace('\\', '/'), Url = saveFileUrl
            };

            return(Json(image));
        }
        public static bool IsAllowedFileType(this HttpPostedFileBase file)
        {
            if (file.HasFile() == false)
            {
                return(false);
            }

            string mimeType = file.ContentType;

            if (mimeType.In("text/plain", "application/x-msaccess", "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/onenote", "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.visio", "application/pdf", "application/vnd.visio2013", "image/bmp", "image/gif", "image/jpeg", "image/png", "application/zip"))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public static bool IsWebFriendlyImage(HttpPostedFileBase file)
        {
            if (file.HasFile() == false)
            {
                return(false);
            }

            if (file.ContentLength > 2 * 1024 * 1024 || file.ContentLength < 1024)
            {
                return(false);
            }
            try
            {
                using (var img = Image.FromStream(file.InputStream))
                {
                    return(ImageFormat.Jpeg.Equals(img.RawFormat) ||
                           ImageFormat.Png.Equals(img.RawFormat) ||
                           ImageFormat.Gif.Equals(img.RawFormat));
                }
            } catch { return(false); }
        }
Beispiel #10
0
        public string UploadSupplierLogo()
        {
            HttpPostedFileBase fileData = Request.Files[0];
            int newImgWidth             = 0;
            int newImgHeight            = 0;


            if (!fileData.HasFile())
            {
                return(JsonHelper.ToJson(new ImageView()
                {
                    Error = 1, Message = "上載的圖片无效!"
                }));
            }
            if (fileData.ContentLength > (512 * 1024))
            {
                return(JsonHelper.ToJson(new ImageView()
                {
                    Error = 1, Message = "上載的圖片尺寸不能超过500KB!"
                }));
            }

            string uploadFileName = fileData.FileName;
            string imageExtension = Path.GetExtension(uploadFileName);

            if (!ValidateImageExtension(imageExtension))
            {
                return(JsonHelper.ToJson(new ImageView()
                {
                    Error = 1, Message = "不允許上載“" + imageExtension + "”格式的圖片!"
                }));
            }


            string saveFilePath = string.Empty;
            string saveFileDir  = ConfigHelper.SharePath + PathHelper.GetSavePathImg();

            if (!Directory.Exists(saveFileDir))
            {
                Directory.CreateDirectory(saveFileDir);
            }

            saveFilePath = saveFileDir + StringHelper.GetRandomString(12) + imageExtension;
            fileData.SaveAs(saveFilePath);

            Bitmap aImg = new Bitmap(saveFilePath);
            Bitmap b    = LTImage.ResizeImage(aImg, 300, 300);

            newImgWidth  = b.Width;
            newImgHeight = b.Height;

            if (fileData.ContentLength > (1024 * 500))//如果大于500k,那么就需要重新压缩图片了
            {
                string saveFileDirNew = ConfigHelper.SharePath + PathHelper.GetSavePathImg();

                string saveFilePathNew = saveFileDirNew + StringHelper.GetRandomString(12) + imageExtension;

                ReCompressImage(saveFilePath, saveFilePathNew);

                saveFilePath = saveFilePathNew;
            }

            string saveImg200 = saveFilePath.Replace(imageExtension, "_218" + imageExtension);

            SaveProductImageSizeOld(saveFilePath.Replace(ConfigHelper.SharePath, ""), saveImg200, 218, 218);


            ImageView result = new ImageView()
            {
                Url  = saveFilePath.Replace(ConfigHelper.SharePath, ConfigHelper.ImageServer).Replace("\\", "//"),
                Path = saveFilePath.Replace(ConfigHelper.SharePath, ""),
            };


            return(JsonHelper.ToJson(result));
        }
Beispiel #11
0
        /// <summary>
        /// 上传商品图片
        /// </summary>
        /// <returns></returns>
        public JsonResult UploadImage(bool isTemp = false, int cutWidth = 0)
        {
            //相对路径
            string             relativePath = string.Empty;
            string             url = string.Empty;
            int                width = 0, height = 0;
            HttpPostedFileBase fileData = Request.Files[0];

            if (!fileData.HasFile())
            {
                return(Json(new ImageView()
                {
                    Error = 1, Message = "上載的圖片无效!"
                }));
            }
            if (fileData.ContentLength > (2 * 1024 * 1024))
            {
                return(Json(new ImageView()
                {
                    Error = 1, Message = "上載的圖片尺寸不能超过2M!!"
                }));
            }
            try
            {
                string uploadFileName = fileData.FileName;
                string imageExtension = Path.GetExtension(uploadFileName);

                if (!ValidateImageExtension(imageExtension))
                {
                    return(Json(new ImageView()
                    {
                        Error = 1, Message = "不允許上載“" + imageExtension + "”格式的圖片!"
                    }));
                }
                else
                {
                    string relativeDir = PathHelper.GetSaveSjPathImg();

                    if (isTemp)//保存到临时路径下
                    {
                        relativeDir = PathHelper.GetSavePathTemp();
                    }

                    CheckOrCreateDirectory(ConfigHelper.SharePath + relativeDir);

                    var fileName = StringHelper.GetRandomString(12);
                    //保存原图
                    relativePath = relativeDir + fileName + imageExtension;
                    var absolutePath = ConfigHelper.SharePath + relativePath;
                    fileData.SaveAs(absolutePath);

                    //重新压缩图片
                    if (fileData.ContentLength > (1024 * 500))//如果大于500k,那么就需要重新压缩图片了
                    {
                        string relativeDirNew = PathHelper.GetSaveSjPathImg();;
                        if (isTemp)//保存到临时路径下
                        {
                            relativeDirNew = PathHelper.GetSavePathTemp();
                        }

                        CheckOrCreateDirectory(ConfigHelper.SharePath + relativeDirNew);

                        fileName = StringHelper.GetRandomString(12);
                        string relativePathNew = relativeDirNew + fileName + imageExtension;
                        string absolutePathnew = ConfigHelper.SharePath + relativePathNew;
                        string urlNew          = ConfigHelper.ImageServer + relativePathNew.Replace('\\', '/');

                        ReCompressImage(absolutePath, absolutePathnew);

                        relativePath = relativePathNew;
                        absolutePath = absolutePathnew;
                        url          = urlNew;
                    }

                    //这个为了剪切功能生成图片大小
                    Bitmap originalImg = new Bitmap(absolutePath);
                    width  = originalImg.Width;
                    height = originalImg.Height;
                    if (width < 300 || height < 300)
                    {
                        return(Json(new ImageView {
                            Error = 1, Message = "上載的圖片尺寸不能小於300x300"
                        }));
                    }
                    #region 生成缩略图
                    var thumbsDir = Path.GetDirectoryName(absolutePath);

                    EncoderParameters parms = new EncoderParameters(1);
                    var imgCodecInfo        = GetImageCodecInfo(GetImageFormat(imageExtension));
                    parms.Param[0] = new EncoderParameter(Encoder.Quality, ((long)80));

                    //切640的图
                    Bitmap b640       = LTImage.ResizeImage(originalImg, 640, 640, true, true, true);
                    string imgPath640 = thumbsDir + "\\" + fileName + "_640" + imageExtension;
                    b640.Save(imgPath640, imgCodecInfo, parms);
                    b640.Dispose();
                    //切180的图
                    Bitmap b180 = LTImage.ResizeImage(originalImg, 180, 180, true, true, true);
                    originalImg.Dispose();
                    string imgPath180 = thumbsDir + "\\" + fileName + "_180" + imageExtension;
                    b180.Save(imgPath180, imgCodecInfo, parms);
                    b180.Dispose();
                    #endregion
                    url = ConfigHelper.ImageServer + relativePath.Replace('\\', '/');
                }
            }
            catch (Exception ex)
            {
                // LogHelper.GetLogger(typeof(UtilityController)).Error("上传失败:" + ex.ToString());
                return(Json(new ImageView {
                    Error = 1, Message = ex.Message
                }));
            }

            return(Json(new ImageView {
                Url = url, Path = relativePath, Width = width, Height = height
            }));
        }
Beispiel #12
0
        /// <summary>
        /// 商品上传及自动剪切
        /// </summary>
        /// <returns></returns>
        public JsonResult UploadImageAndCut()
        {
            string             relativePath = string.Empty;
            string             url          = string.Empty;
            ImageView          imageView    = new ImageView();
            HttpPostedFileBase fileData     = Request.Files[0];

            if (!fileData.HasFile())
            {
                return(Json(new ImageView()
                {
                    Error = 1, Message = "上載的圖片无效!"
                }));
            }
            if (fileData.ContentLength > (2 * 1024 * 1024))
            {
                return(Json(new ImageView()
                {
                    Error = 1, Message = "上載的圖片尺寸不能超过2M!!"
                }));
            }
            try
            {
                string uploadFileName = fileData.FileName;
                string imageExtension = Path.GetExtension(uploadFileName);

                if (!ValidateImageExtension(imageExtension))
                {
                    return(Json(new ImageView()
                    {
                        Error = 1, Message = "不允許上載“" + imageExtension + "”格式的圖片!"
                    }));
                }
                else
                {
                    string relativeDir = PathHelper.GetSaveSjPathImg();

                    CheckOrCreateDirectory(ConfigHelper.SharePath + relativeDir);

                    //保存原图
                    relativePath = relativeDir + StringHelper.GetRandomString(12) + imageExtension;
                    var absolutePath = ConfigHelper.SharePath + relativePath;
                    fileData.SaveAs(absolutePath);

                    url = ConfigHelper.ImageServer + relativePath.Replace('\\', '/');


                    //重新压缩图片
                    if (fileData.ContentLength > (1024 * 500)) //如果大于500k,那么就需要重新压缩图片了
                    {
                        string relativeDirNew  = PathHelper.GetSavePathTemp();
                        string relativePathNew = relativeDirNew + StringHelper.GetRandomString(12) + imageExtension;
                        string absolutePathnew = ConfigHelper.SharePath + relativePathNew;
                        string urlNew          = ConfigHelper.ImageServer + relativePathNew.Replace('\\', '/');

                        ReCompressImage(absolutePath, absolutePathnew);

                        relativePath = relativePathNew;
                        url          = urlNew;
                    }

                    //这个为了剪切功能生成图片大小
                    imageView = CutImageAndReturnPath(false, absolutePath, 0);
                }
            }
            catch (Exception ex)
            {
                // LogHelper.GetLogger(typeof(UtilityController)).Error("上传失败:" + ex.ToString());
            }

            return(Json(imageView));
        }