文件上传(asp.net webform中)

时间:2023-03-09 15:38:21
文件上传(asp.net webform中)

1.配置允许上传文件大小

 <configuration>

   <appSettings>
<!--配置上传文件最大字节数:单位KB-->
<add key="PhysicsObjectLength" value="30720"/>
</appSettings>
<system.web> <!--设置请求的最大字节数(默认是4096,单位:KB)-->
<httpRuntime maxRequestLength="40960"></httpRuntime>
<compilation debug="true" targetFramework="4.0" />
</system.web> </configuration>

2.aspx

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo09_UpLoad.aspx.cs" Inherits="WebApp.Demo09_UpLoad" %>

 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
请选择要上传的文件:<asp:FileUpload ID="ful" runat="server" />
&nbsp;&nbsp;
<asp:Button ID="btnUpload" runat="server" Text="开始上传" OnClick="btnUpload_Click" />
<br />
<br />
<asp:Literal ID="ltaMsg" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>

3.aspx.cs

 protected void btnUpload_Click(object sender, EventArgs e)
{
//【1】判断文件是否存在
if (!this.ful.HasFile) return;
//【2】获取文件大小,判断是否符合设置要求(变成MB)
double fileLength = this.ful.FileContent.Length / (1024.0 * 1024.0);
//获取配置文件中上传文件大小的限制
double limitedLength = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["PhysicsObjectLength"]);
limitedLength = limitedLength / 1024.0;//转换成MB单位
//判断实际文件大小是否符合要求
if (fileLength > limitedLength)
{
// this.ltaMsg.Text = "上传文件大小不能超过" + limitedLength + "MB";
this.ltaMsg.Text = "<script type='text/javascript'>alert('上传文件最大不能超过" + limitedLength + "M')</script>";
return;
}
//【3】获取文件名,判断文件扩展是否符合要求
string fileName = this.ful.FileName;
//判断文件名是否是exe文件
if (fileName.Substring(fileName.LastIndexOf(".") + ).ToLower() == "exe")
{
this.ltaMsg.Text = "<script type='text/javascript'>alert('上传文件不能是exe文件')</script>";
return;
}
//修改文件名
fileName = DateTime.Now.ToString("yyyyMMddhhssms") + "_" + fileName; //【4】获取服务器文件夹路径
string path = Server.MapPath("~/UploadFiles");
//【5】上传文件
try
{
this.ful.SaveAs(path + "/" + fileName);
this.ltaMsg.Text = "<script type='text/javascript'>alert('文件上传成功!')</script>";
}
catch (Exception ex)
{
this.ltaMsg.Text = "<script type='text/javascript'>alert('文件上传失败!" + ex.Message + "')</script>";
}
}