您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 丹东分类信息网,免费分类信息发布

asp.net判断上传文件类型的三种方法

2024/4/13 19:42:49发布14次查看
一、 安全性比较低,把文本文件1.txt改成1.jpg照样可以上传,但其实现方法容易理解,实现也简单,所以网上很多还是采取这种方法。
boolean fileok = false; string path = server.mappath("~/images/"); //判断是否已经选取文件 if (fileupload1.hasfile) { //取得文件的扩展名,并转换成小写 string fileextension = system.io.path.getextension(fileupload1.filename).tolower(); //限定只能上传jpg和gif图片 string[] allowextension = { ".jpg", ".gif" }; //对上传的文件的类型进行一个个匹对 int j = 0; for (int i = 0; i < allowextension.length; i++) { if (fileextension == allowextension[i]) { fileok = true; return; } else { j++; } } if (j > 0) { response.write("<script>alert('文件格式不正确');</script>"); return; } } else { response.write("<script>alert('你还没有选择文件');</script>"); return; } //如果扩展名符合条件,则上传 if (fileok) { fileupload1.postedfile.saveas(path + fileupload1.filename); response.write("<script>alert('上传成功');</script>"); }
二、不检测文件后缀而是检测文件mime内容类型。
boolean fileok = false; string path = server.mappath("~/images/"); //判断是否已经选取文件 if (fileupload1.hasfile) { //取得文件mime内容类型 string type = this.fileupload1.postedfile.contenttype.tolower(); if (type.contains("image")) //图片的mime类型为"image/xxx",这里只判断是否图片。 { fileok = true; } else { response.write("<script>alert('格式不正确')</script>"); } } else { response.write("<script>alert('你还没有选择文件');</script>"); } //如果扩展名符合条件,则上传 if (fileok) { fileupload1.postedfile.saveas(path + fileupload1.filename); response.write("<script>alert('上传成功');</script>"); }
三、可以实现真正意义上的文件类型判断
try { //判断是否已经选取文件 if (fileupload1.hasfile) { if (isallowedextension(fileupload1)) { string path = server.mappath("~/images/"); fileupload1.postedfile.saveas(path + fileupload1.filename); response.write("<script>alert('上传成功');</script>"); } else { response.write("<script>alert('您只能上传jpg或者gif图片');</script>"); } } else { response.write("<script>alert('你还没有选择文件');</script>"); } } catch (exception error) { response.write(error.tostring()); } #endregion } //真正判断文件类型的关键函数 public static bool isallowedextension(fileupload hifile) { system.io.filestream fs = new system.io.filestream(hifile.postedfile.filename, 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 { } r.close(); fs.close(); if (fileclass == "255216" || fileclass == "7173")//说明255216是jpg;7173是gif;6677是bmp,13780是png;7790是exe,8297是rar { return true; } else { return false; } }
丹东分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录