本篇文章为大家展示了asp.net 中怎么使用fileupload控件上传图片,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
页面代码:
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="上传" Width="54px" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="" Style="color: Red"></asp:Label>
<asp:Image runat="server" ID="Image1" Style="z-index: 102; left: 20px; position: absolute;
top: 49px" Width="73px" />
</div>
</form>
后台代码:
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;
namespace Web.File
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region 文件上传
/// <summary>
/// 文件上传
/// </summary>
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.FileName == "")
{
this.Label1.Text = "上传文件不能为空";
return;
}
bool fileIsValid = false;
//如果确认了上传文件,则判断文件类型是否符合要求
if (this.FileUpload1.HasFile)
{
//获取上传文件的后缀
String fileExtension = System.IO.Path.GetExtension(this.FileUpload1.FileName).ToLower();
String[] restrictExtension = { ".gif", ".jpg", ".bmp", ".png" };
//判断文件类型是否符合要求
for (int i = 0; i < restrictExtension.Length; i++)
{
if (fileExtension == restrictExtension[i])
{
fileIsValid = true;
}
//如果文件类型符合要求,调用SaveAs方法实现上传,并显示相关信息
if (fileIsValid == true)
{
//上传文件是否大于10M
if (FileUpload1.PostedFile.ContentLength > (10 * 1024 * 1024))
{
this.Label1.Text = "上传文件过大";
return;
}
try
{
this.Image1.ImageUrl = "~/File/" + FileUpload1.FileName;
this.FileUpload1.SaveAs(Server.MapPath("~/File/") + FileUpload1.FileName);
this.Label1.Text = "文件上传成功!";
}
catch
{
this.Label1.Text = "文件上传失败!";
}
finally
{
}
}
else
{
this.Label1.Text = "只能够上传后缀为.gif,.jpg,.bmp,.png的文件";
}
}
}
}
#endregion
}
}
Web.config 配置:
<!--因为FileUpload 控件上传最大为4M,如果要上传更大文件,改下maxRequestLength的大小-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime requestValidationMode="2.0" maxRequestLength="10485760" executionTimeout="3600" appRequestQueueLimit="10000"/>
</system.web>
</configuration>
上述内容就是asp.net 中怎么使用fileupload控件上传图片,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。