//定义了两个file对象
HttpPostedFileBase file = Request.Files["FileData"]; HttpPostedFileBase file_check = Request.Files["FileData"];
if (file == null || file.ContentLength == 0) { return Json(new AjaxResponse() { Success = false, Message = "获取上传文件失败", Data = "" }); }
//传递其中一个file_check过去进行类型检测
if (!Utils.CheckFileExtension(file_check, new string[] { "doc", "docx" })) { return Json(new AjaxResponse() { Success = false, Message = "文件格式错误", Data = "" }); }
public static bool CheckFileExtension(HttpPostedFileBase file_check, string[] exts) { bool ret = false; Stream fs = file_check.InputStream; BinaryReader r = new BinaryReader(fs); string fileclass = ""; byte buffer; try { buffer = r.ReadByte(); fileclass = buffer.ToString(); buffer = r.ReadByte(); fileclass += buffer.ToString(); } catch { return false; } //close之后 两个file对象 都没有内容了。... r.Close(); fs.Close(); foreach(string ext in exts) { if(GetFileExtension(ext).Equals(fileclass)) { ret = true; break; } } return ret; } public static string GetFileExtension(string ext) { switch(ext.ToLower()) { case "jpg": return "255216"; case "jpeg": return "255216"; case "gif": return "7173"; case "bmp": return "6677"; case "png": return "13780"; case "com": return "7790"; case "exe": return "7790"; case "dll": return "7790"; case "rar": return "8297"; case "xml": return "6063"; case "html": return "6033"; case "aspx": return "239187"; case "asp": return "239187"; case "cshtml": return "239187"; case "css": return "6499"; case "cs": return "117115"; case "js": return "4742"; case "sql": return "1310"; case "bat": return "64101"; case "btseed": return "10056"; case "rdp": return "255254"; case "psd": return "5666"; case "pdf": return "3780"; case "chm": return "7384"; case "log": return "70105"; case "reg": return "8269"; case "hlp": return "6395"; case "doc": return "208207"; case "xls": return "208207"; case "ppt": return "208207"; case "wps": return "208207"; case "docx": return "8075"; case "xlsx": return "8075"; case "pptx": return "8075"; case "zip": return "8075"; case "accdb": return "01"; case "mdb": return "01"; default:return ""; } }
close之后 两个file对象 都没有内容了。...这是怎么回事.
HttpPostedFile file = Request.Files[0];
变量file只是对文件的引用,对file的任何操作都直接影响到已经上载的文件
看来得先保存在操作了 或者 不close,外面操作完了再close
2016-07-01: 发现不close 可以上传文件 ,但是 文件已被损坏......
buffer = r.ReadByte(); fileclass = buffer.ToString(); buffer = r.ReadByte(); fileclass += buffer.ToString();
为什么要ReadByte()两次呢?
因为是通过文件的前两个字节判断的文件类型,如果不readbyte两次,也可以用循环,按下标取两个