C#上傳圖片(含有圖片大小格式過濾以及改變像素安全存儲)


示例一:

public JsonResult Upload(string parameter)
        {
            var file = Request.Files[0];
            try
            {
                //LogHelper.Info("文件長度:" + file.ContentLength.ToString() + "||最大照片:" + 1024 * 1024 * (Config.UploadFileSizeLimitInMB) + "||" + Config.UploadFileSizeLimitInMB);
                if (file == null || file.ContentLength == 0)
                {
                    throw new ValidationException("無上傳文件");
                }
                if (file.ContentLength > 1024 * 1024 * Convert.ToInt32(uploadFileSize))
                {
                    throw new ValidationException("上傳文件過大");
                }
                #region checkfile
                string fType = file.ContentType;//獲取圖像的類型  

                bool isimage = fType == "image/bmp" || fType == "image/gif" || fType == "image/pjpeg" || fType == "image/jpeg" || fType == "image/x-png" || fType == "image/png";

                if (fType == "application/octet-stream")
                {
                    BinaryReader reader = new BinaryReader(file.InputStream);
                    string fileClass;
                    byte buffer;
                    buffer = reader.ReadByte();
                    fileClass = buffer.ToString();
                    buffer = reader.ReadByte();
                    fileClass += buffer.ToString();
                    //reader.Close();
                    if (!(fileClass == "255216" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677"))
                    //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
                    {
                        throw new ValidationException("請上傳圖片格式的文件");
                    }
                    else
                    {
                        isimage = true;
                    }

                    file.InputStream.Position = 0;
                }

                string fext = Path.GetExtension(file.FileName).ToLower(); //獲取文件后綴

                bool fextIsImage = fext == ".bmp" || fext == ".gif" || fext == ".png" || fext == ".jpeg" || fext == ".jpe" || fext == ".jpg";

                if (!(isimage && fextIsImage))
                {
                    throw new ValidationException("請上傳圖片格式的文件");
                }
                #endregion

                string uploadPath = string.Format("{0}\\{1}", uploadFilePath, SqlTimeHelper.GetTime().ToString("yyyyMMdd"));
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                var fileId = Guid.NewGuid();

                System.Drawing.Image sImage = System.Drawing.Image.FromStream(file.InputStream);
                int tw = sImage.Width - 1;
                int th = sImage.Height - 1;
                WatermarkHelper.AddWartermark(sImage);

                ImagesHelper.DrawImage(sImage, string.Format("{0}\\{1}{2}", uploadPath, fileId, fext), tw, 50);

                ////原始圖片的寬度和高度  
                //System.Drawing.Bitmap objPic, objNewPic;  //圖像對象
                //objPic = new System.Drawing.Bitmap(sImage);
                //objNewPic = new System.Drawing.Bitmap(objPic, tw, th);  //使用指定的大小初始化objNewPic
                //objNewPic.Save(string.Format("{0}\\{1}{2}", uploadPath, fileId, fext));
                //objPic.Dispose();
                //objNewPic.Dispose();
                sImage.Dispose();  //釋放資源

                var rtnJson = Resource.SaveFile(file.FileName, fileId, fext);

                //下面這句代碼缺少的話,上傳成功后上傳隊列的顯示不會自動消失
                return Json(new ApiSuccessResponse<FileUploadModel>(rtnJson));
            }
            catch (ValidationException ve)
            {
                return Json(new ApiInvalidParaExceptionResponse(ve.Message));
            }
            catch (Exception ue)
            {
                return Json(new ApiExceptionResponse<string>(ue));
            }
        }

示例二:

 public bool SaveStringToFile(string token, string fileName, string content)
        {
            try
            {
                string fext = Path.GetExtension(fileName).ToLower(); //獲取文件后綴
                bool fextIsImage = fext == ".bmp" || fext == ".gif" || fext == ".png" || fext == ".jpeg" || fext == ".jpe" || fext == ".jpg";

                byte[] filecontent = System.Convert.FromBase64String(content);
                string path = System.Configuration.ConfigurationSettings.AppSettings["UploadFilePath"];
                BinaryReader reader = new BinaryReader(new MemoryStream(filecontent));
                string fileClass;
                byte buffer;
                buffer = reader.ReadByte();
                fileClass = buffer.ToString();
                buffer = reader.ReadByte();
                fileClass += buffer.ToString();
                reader.Close();
                bool isimage = false;
                if (!(fileClass == "255216" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677"))
                //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
                {
                    return false;
                }
                else
                {
                    isimage = true;
                }

                if (!(isimage && fextIsImage))
                {
                    return false;
                }
                path = Path.Combine(path, fileName);
                FileInfo info = new FileInfo(path);
                if (!Directory.Exists(info.DirectoryName))
                    Directory.CreateDirectory(info.DirectoryName);
                if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
                System.IO.FileStream outfile = System.IO.File.OpenWrite(path);
                outfile.Write(filecontent, 0, filecontent.Length);
                outfile.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM