/// <summary> ///Check whether the file is a picture and save/// </summary> /// <param name= "file" >file</param> /// <param name= "Savepath" >directory where files are saved (example:/img/mark/)</param> /// <param name= "NewFileName" >name of the file after renaming</param> /// <returns>is successful</returns> Private BOOLSaveImage (httppostedfilebase file,stringSavepath, out stringNewFileName) { BOOLISSUC =false; NewFileName=string. Empty; intContentlen =file. ContentLength; byte[] Filebyte =New byte[2]; using(Stream stream =file. InputStream) {stream. Read (Filebyte,0,2); stringFileflag =string. Empty; if(Filebyte! =NULL&& filebyte.length >0) {Fileflag= filebyte[0]. ToString () + filebyte[1]. ToString (); Dictionary<string,string> dicimagebyte =Newdictionary<string,string> { { "255216","jpg"},{"7173","gif"},{"6677","BMP"},{"13780","PNG"} }; stringImageType =string. Empty; BOOLIsimage = Dicimagebyte.trygetvalue (Fileflag, outImageType); if(isimage) {stringFileName = Guid.NewGuid (). ToString () +"."+ImageType; File. SaveAs (Path.Combine (Server.MapPath (Savepath), fileName)); NewFileName= Savepath +FileName; Issuc=true; }} stream. Close (); returnIssuc; } }
MVC check image format after uploading