asp.net文件上传解决方案(图片上传、单文件上传(3)


else if (IsAllowedExtension(FileUpload1) == true)
即变成服务器端检查上传文件类型。
5、服务器端检查上传文件的类型(文件内部真正的格式)

<body> <form runat="server"> <div> <table> <tr> <td colspan="2"> 服务器检查上传文件类型</td> </tr> <tr> <td> <asp:FileUpload runat="server" /></td> <td> <asp:Button runat="server" Text="上传图片" /></td> </tr> <tr> <td colspan="2"> <asp:Label runat="server" ForeColor="Red"></asp:Label></td> </tr> </table> </div> </form> </body>

后台代码:

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void bt_upload_Click(object sender, EventArgs e) { try { if (FileUpload1.PostedFile.FileName == "") { this.lb_info.Text = "请选择文件!"; } else { string filepath = FileUpload1.PostedFile.FileName; if (IsAllowedExtension(FileUpload1) == true) { string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); string serverpath = Server.MapPath("images/") + filename; FileUpload1.PostedFile.SaveAs(serverpath); this.lb_info.Text = "上传成功!"; } else { this.lb_info.Text = "请上传图片"; } } } catch (Exception error) { this.lb_info.Text = "上传发生错误!原因:" + error.ToString(); } } private static bool IsAllowedExtension(FileUpload upfile) { FileStream fs = new FileStream(upfile.PostedFile.FileName, FileMode.Open, FileAccess.Read); BinaryReader r = new 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"||fileclass=="6677"||fileclass=="13780")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar { return true; } else { return false; } } }

为大家推荐一个专题,供大家学习:《ASP.NET文件上传汇总》

是不是内容很精彩,喜欢的朋友就收藏起来吧,以后在遇到ASP.NET文件上传问题的时候能够有所帮助。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjwpwy.html