.net实现单张图片的上传

前台代码:

代码
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="imgupload._Default" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml" >
 6 <head runat="server">
 7     <title></title>
 8 </head>
 9 <body>
10     <form id="form1" runat="server">
11     <div>
12     
13         <asp:FileUpload ID="FileUpload1" runat="server" />
14         <asp:Button ID="Button1" runat="server" Text="上传" onclick="Button1_Click" />
15         <br />
16         <asp:Image ID="img" runat="server" />
17     
18     </div>
19     </form>
20 </body>
21 </html>
22 

后台代码:

code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 
 8 namespace imgupload
 9 {
10     public partial class _Default : System.Web.UI.Page
11     {
12         protected void Page_Load(object sender, EventArgs e)
13         {
14             this.img.Visible = false;
15         }
16         protected void Button1_Click(object sender, EventArgs e)
17         {
18             string fullfilename = this.FileUpload1.PostedFile.FileName;
19             string filename = fullfilename.Substring(fullfilename.LastIndexOf("\\")+1);
20             string typefilename = fullfilename.Substring(fullfilename.LastIndexOf(".")+1);
21             if (typefilename == "jpg" || typefilename == "gif" || typefilename == "png")
22             {
23                 this.FileUpload1.SaveAs(Server.MapPath("upload"+ "\\" + filename);
24                 this.img.ImageUrl = "upload/" + filename;
25                 this.img.Visible = true;
26                 Response.Write("上传成功");
27             }
28             else
29             {
30                 Response.Write("<script>alert('错误的图片文件格式');history.back();");
31             }
32         }
33     }
34 }
35 
原文地址:https://www.cnblogs.com/yinpeng186/p/1618778.html