.net如何上传图片并且显示在页面上

.net如何上传图片并且显示在页面上,第1张

1.网站根目录下新建一个 文件夹 UploadFiles

//上传文件按钮

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

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11750587.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存