码迷,mamicode.com
首页 > Web开发 > 详细

上传图片到文件夹并显示在GridView控件里面

时间:2014-10-20 19:01:10      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

http://aspsnippets.com/Articles/Upload-images-to-folder-and-display-uploaded-images-in-ASPNet-GridView-using-C-and-VBNet.aspx

1. Html 页面

bubuko.com,布布扣
 <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>
View Code

2. 添加命名空间

using System.IO;
using System.Collections.Generic;

3. 上传文件按钮事件

bubuko.com,布布扣
   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);
            }
        }
View Code


4.Page_Load 事件--加载图片并显示在GridView中

bubuko.com,布布扣
 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();
            }
        }
View Code

 

上传图片到文件夹并显示在GridView控件里面

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/songxia/p/4037940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!