//上传文件按钮
protected void btnUpload_Click(object sender, EventArgs e)
{
string savePath = @"~/UploadFiles"
fudTest 是控件id
//上传文件
if (fudTest.HasFile)
{
try
{
fudTest.SaveAs(Server.MapPath(savePath) + "\\" + fudTest.FileName)
//可以插入数据
Image1.ImageUrl = "~/UploadFiles/" + fudTest.FileName
}
catch (Exception ex)
{
lblerror.Text = "发生错误:" + ex.Message.ToString()
}
}
else
{
lblMessage.Text = "没有选择要上传的文件!"
}
}
前台代码:<div class="mflLeft">
<div class="mflLeft_FileUpload">
<asp:FileUpload ID="mflFileUpload"
runat="server" BorderColor="#6666FF" Width="150px" />
<asp:Button ID="btnUpload" runat="server" Text="点击上传" OnClick="btnUpload_Click" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:Image ID="Image1" runat="server" />
</div>
</div>
后台代码:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (mflFileUpload.HasFile)
{
int a = Convert.ToInt32(ConfigurationManager.AppSettings["maxRequestLength"])
if (mflFileUpload.PostedFile.ContentLength <= Convert.ToInt32(ConfigurationManager.AppSettings["maxRequestLength"]))
{
string extensionName = Path.GetExtension(mflFileUpload.FileName)
if (CheckFileType(extensionName))
{
Random r = new Random()
string fileName = DateTime.Now.ToString("yyyyMMddHHmmssms") + r.Next(1, 9999) + extensionName
string filePath = ConfigurationManager.AppSettings["fileUpPath"] + fileName//图片上传路径
mflFileUpload.SaveAs(Server.MapPath(filePath))//保存上传的图片
Image1.ImageUrl = ConfigurationManager.AppSettings["fileUpPath"] + fileName//显示上传的图片
this.Label1.Text = "文件上传成功!"
}
else {
Response.Write("<script type='text/javascript'>alert('文件格式不正确!')</script>")
return
}
}
else {
Response.Write("<script type='text/javascript'>alert('文件大小不能超过4M!')</script>")
return
}
}
}
protected bool CheckFileType(string fileName)
{
switch (fileName)
{
case ".gif":
return true
case ".png":
return true
case ".jpg":
return true
case ".jpeg":
return true
default:
return false
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)