上传文件检测类型到目前为止我只看到过3种,第一种是检测文件的后缀名;第二种是检测文件的头部编码,不同类型文件的头部编码是不一样的(比如255216是jpg,7173是gif,6677是BMP,13780是PNG,7790是exe,8297是rar等);第三中是检测文件的MIME内容类型。这篇文章代码多有参考网络,特此说明。
前台文件:三种方法的前台文件是一样的.
view source <https://www.cnblogs.com/feelboy/archive/2010/08/19/1803175.html>
print <https://www.cnblogs.com/feelboy/archive/2010/08/19/1803175.html><https://www.cnblogs.com/feelboy/archive/2010/08/19/1803175.html>
1<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><BR><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<A href="<https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd%22%3E>" target=_blank><https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>"></A><BR><html xmlns="<A href="<https://www.w3.org/1999/xhtml%22%C2%A0%3E>" target=_blank>https://www.w3.org/1999/xhtml" ></A><BR><head runat="server"><BR> <title>无标题页</title><BR></head><BR><body><BR> <form id="form1" runat="server"><BR> <div><BR> <asp:FileUpload ID="FileUpload1" runat="server" /><BR> <asp:Button ID="btn_upload" runat="server" <SPAN>OnClick</SPAN>="btn_upload_Click" Text="上传" /><BR> </div><BR> </form><BR></body><BR></html>
后台文件:
第一种方法:安全性相对第二种低,把文本文件1.txt改成1.jpg照样可以上传,但其实现方法容易理解,实现也简单,所以网上很多还是采取这种方法。
01public partial class _Default : System.Web.UI.Page
02{
03 protected void btn_upload_Click(object sender, EventArgs e)
04 {
05 Boolean fileOk = false;
06 string path = Server.MapPath("~/images/");
07 //判断是否已经选取文件
08 if (FileUpload1.HasFile)
09 {
10 //取得文件的扩展名,并转换成小写
11 string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
12 //限定只能上传jpg和gif图片
13 string[] allowExtension = { ".jpg", ".gif" };
14 //对上传的文件的类型进行一个个匹对
15 for (int i = 0; i < allowExtension.Length; i++)
16 {
17 if (fileExtension == allowExtension[i])
18 {
19 fileOk = true;
20 break;
21 }
22 }
23 }
24 else
25 {
26 Response.Write("<script>alert('你还没有选择文件');</script>");
27 }
28 //如果扩展名符合条件,则上传
29 if (fileOk)
30 {
31 FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);
32 Response.Write("<script>alert('上传成功');</script>");
33 }
34 }
35}
第二种方法,可以实现真正意义上的文件类型判断。
01public partial class _Default : System.Web.UI.Page
02{
03 protected void btn_upload_Click(object sender, EventArgs e)
04 {
05 try
06 {
07 //判断是否已经选取文件
08 if (FileUpload1.HasFile)
09 {
10 if (IsAllowedExtension(FileUpload1))
11 {
12 string path = Server.MapPath("~/images/");
13 FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);
14 Response.Write("<script>alert('上传成功');</script>");
15 }
16 else
17 {
18 Response.Write("<script>alert('您只能上传jpg或者gif图片');</script>");
19
关键词标签:asp.net
相关阅读
热门文章 手把手教你用好LINQ to SQL在.NET环境下为网站增加IP过滤功能ASP.NET 如何避免页面重新整理时重复送出用Asp.net扩展ExtJS
人气排行 asp.net表单提交方法GET\POST在ASP.NET中如何判断用户IE浏览器的版本Asp.net中messagebox的实现方法Asp.net中的web.config配置在ASP.NET MVC中实现大文件异步上传用Iformattable接口控制.Net中文本格式c#.Net经典面试题目用Asp.net扩展ExtJS
查看所有0条评论>>