ASP.NET WEB开发,实现上传图片

时间:2022-06-01 16:36:31
protected void btnUp_Click(object sender, EventArgs e)
{ Boolean fileOK = false;
String path = Server.MapPath("~/UploadedImages/");
if (fileUpLoad.HasFile)
{
String fileExtension =
System.IO.Path.GetExtension(fileUpLoad.FileName).ToLower();
String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
for (int i = ; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
} if (fileOK)
{
try
{
fileUpLoad.PostedFile.SaveAs(path
+ fileUpLoad.FileName);
Label1.Text = "File uploaded!";
}
catch (Exception ex)
{
Label1.Text = "File could not be uploaded." + ex.ToString();
}
}
else
{
Label1.Text = "Cannot accept files of this type.";
} }

设计界面的代码如下

 <form id="form1" runat="server">
<div> <asp:FileUpload ID="fileUpLoad" runat="server" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<p>
<asp:Button ID="btnUp"
runat="server" Text="上传" onclick="btnUp_Click" />
</p>
</div>
</form>

默认限制上传的大小为4M=4096

在web.Config中进行设置,代码如下在<System.Web></System.Web>:

  <httpRuntime maxRequestLength="" executionTimeout=""/>