1.配置允许上传文件大小
1 <configuration> 2 3 <appSettings> 4 <!--配置上传文件最大字节数:单位KB--> 5 <add key="PhysicsObjectLength" value="30720"/> 6 </appSettings> 7 <system.web> 8 9 <!--设置请求的最大字节数(默认是4096,单位:KB)--> 10 <httpRuntime maxRequestLength="40960"></httpRuntime> 11 <compilation debug="true" targetFramework="4.0" /> 12 </system.web> 13 14 </configuration>
2.aspx
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo09_UpLoad.aspx.cs" Inherits="WebApp.Demo09_UpLoad" %> 2 3 <!DOCTYPE html> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 8 <title></title> 9 </head> 10 <body> 11 <form id="form1" runat="server"> 12 <div> 13 请选择要上传的文件:<asp:FileUpload ID="ful" runat="server" /> 14 15 <asp:Button ID="btnUpload" runat="server" Text="开始上传" OnClick="btnUpload_Click" /> 16 <br /> 17 <br /> 18 <asp:Literal ID="ltaMsg" runat="server"></asp:Literal> 19 </div> 20 </form> 21 </body> 22 </html>
3.aspx.cs
1 protected void btnUpload_Click(object sender, EventArgs e) 2 { 3 //【1】判断文件是否存在 4 if (!this.ful.HasFile) return; 5 //【2】获取文件大小,判断是否符合设置要求(变成MB) 6 double fileLength = this.ful.FileContent.Length / (1024.0 * 1024.0); 7 //获取配置文件中上传文件大小的限制 8 double limitedLength = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["PhysicsObjectLength"]); 9 limitedLength = limitedLength / 1024.0;//转换成MB单位 10 //判断实际文件大小是否符合要求 11 if (fileLength > limitedLength) 12 { 13 // this.ltaMsg.Text = "上传文件大小不能超过" + limitedLength + "MB"; 14 this.ltaMsg.Text = "<script type='text/javascript'>alert('上传文件最大不能超过" + limitedLength + "M')</script>"; 15 return; 16 } 17 //【3】获取文件名,判断文件扩展是否符合要求 18 string fileName = this.ful.FileName; 19 //判断文件名是否是exe文件 20 if (fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower() == "exe") 21 { 22 this.ltaMsg.Text = "<script type='text/javascript'>alert('上传文件不能是exe文件')</script>"; 23 return; 24 } 25 //修改文件名 26 fileName = DateTime.Now.ToString("yyyyMMddhhssms") + "_" + fileName; 27 28 //【4】获取服务器文件夹路径 29 string path = Server.MapPath("~/UploadFiles"); 30 //【5】上传文件 31 try 32 { 33 this.ful.SaveAs(path + "/" + fileName); 34 this.ltaMsg.Text = "<script type='text/javascript'>alert('文件上传成功!')</script>"; 35 } 36 catch (Exception ex) 37 { 38 this.ltaMsg.Text = "<script type='text/javascript'>alert('文件上传失败!" + ex.Message + "')</script>"; 39 } 40 }