1. Html 页面
<div> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /><hr /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowHeader="false"> <Columns> <asp:BoundField DataField="Text" /> <asp:ImageField DataImageUrlField="Value" ControlStyle-Height="100" ControlStyle-Width="100" /> </Columns> </asp:GridView> </div>
2. 添加命名空间
using System.IO; using System.Collections.Generic;
3. 上传文件按钮事件
protected void btnUpload_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName); FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Image/") + fileName); Response.Redirect(Request.Url.AbsoluteUri); } }
4.Page_Load 事件--加载图片并显示在GridView中
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string[] filePaths = Directory.GetFiles(Server.MapPath("~/Image/")); List<ListItem> files = new List<ListItem>(); foreach (string filePath in filePaths) { string fileName = Path.GetFileName(filePath); files.Add(new ListItem(fileName, "~/Image/" + fileName)); } GridView1.DataSource = files; GridView1.DataBind(); } }
时间: 2024-10-12 12:45:04