日期:2014-05-18 浏览次数:20465 次
public bool CheckImgFormat(string fileExt, string contentType) { string Extlist = ".BMP.GIF.JPEG.JPG.PNG"; if (Extlist.IndexOf(fileExt) == -1) { return false; } else { string conType = "image/pjpeg image/gif image/bmp image/x-png image/tiff image/png image/jpeg"; if (conType.IndexOf(contentType) == -1) { return false; } else { return true; } } }
String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();//获取文件扩展名 String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" }; //允许上传的文件格式 for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) { fileOK = true; break; }
------解决方案--------------------
例子
<%@ Page Language="C#" EnableEventValidation="false" EnableViewState="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> private bool IsAllowedExtension(String filePath) { bool ret = false; System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader r = new System.IO.BinaryReader(fs); string fileclass = ""; byte buffer; try { buffer = r.ReadByte(); fileclass = buffer.ToString(); buffer = r.ReadByte(); fileclass += buffer.ToString(); } catch { return false; } r.Close(); fs.Close(); /*文件扩展名说明 *4946/104116 txt *7173 gif *255216 jpg *13780 png *6677 bmp *239187 txt,aspx,asp,sql *208207 xls.doc.ppt *6063 xml *6033 htm,html *4742 js *8075 xlsx,zip,pptx,mmap,zip *8297 rar *01 accdb,mdb *7790 exe,dll *5666 psd *255254 rdp *10056 bt种子 *64101 bat *4059 sgf */ String[] fileType = { "255216", "7173", "6677", "13780" }; String[] fileExtName = { "jpg", "gif", "bmp", "png" }; /* //纯图片 String[] fileType = { "7173", //gif "255216", //jpg "13780" //png }; */ String fExt = ""; for (int i = 0; i < fileType.Length; i++) { if (fileclass == fileType[i]) { fExt = fileExtName[i]; ret = true; break; } } System.Web.HttpContext.Current.Response.Write(fExt);//可以在这里输出你不知道的文件类型的扩展名 return ret; } protected void Button1_Click(object sender, EventArgs e) { String g = System.Guid.NewGuid().ToString("D"); FileUpload1.SaveAs(Server.MapPath("~/" + g + ".tmp")); if (IsAllowedExtension(Server.MapPath("~/" + g + ".tmp"))) { FileUpload1.SaveAs(Server.MapPath("~/x.jpg")); } System.IO.File.Delete(Server.MapPath("~/" + g + ".tmp")); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1"