user4416997
user4416997

Reputation:

To bind images in repeater using asp.net

In the below code i have a repeater and i want to bind the images from local drive to repeater.But the image is not binding but i can get the image name from the local drive pls help me to solve the issue.

  string[] filePaths = Directory.GetFiles("D:\\Users\\Images\\Pictures\\");
            List<ListItem> files = new List<ListItem>();
            foreach (string filePath in filePaths)
            {
                string fileName = Path.GetFileName(filePath);
                files.Add(new ListItem(fileName, @"D:\Users\Images\Pictures\" + fileName)); //i can get image name  --D:\Users\Images\Pictures\flight.jpg
            }
            Repeater1.DataSource = files;
            Repeater1.DataBind();


 <asp:Repeater ID="Repeater1" runat="server">
                        <ItemTemplate>
                            <li>
                                <img src='<%# DataBinder.Eval(Container.DataItem,"Value") %>' title='<%# (DataBinder.Eval(Container.DataItem,"Text").ToString()).Split('.')[0].ToString() %>' alt=""></li>
                        </ItemTemplate>
                    </asp:Repeater>

Upvotes: 1

Views: 2001

Answers (1)

Win
Win

Reputation: 62260

Client cannot download a file outside of web application's folder. You have two options -

Option 1

Keep images inside a folder of the web application. For example,

enter image description here

Option 2

Create a GenericHandler.

Note: When your application moves to production, You need to make sure D:\Users\Images folder exists in web server.

public class ImageHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string fileName = context.Request.QueryString["filename"];
        context.Response.ContentType = "image/jpeg";
        context.Response.TransmitFile(@"D:\Users\Images\Pictures\" + fileName);
    }

    public bool IsReusable
    {
        get { return false; }
    }
}

ASPX
<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:Image runat="server" 
            ImageUrl='<%# "~/ImageHandler.ashx?filename=" + Eval("Value") %>' />
    </ItemTemplate>
</asp:Repeater>

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string[] filePaths = Directory.GetFiles(@"D:\Users\Images\Pictures");
        List<ListItem> files = new List<ListItem>();
        foreach (string filePath in filePaths)
        {
            string fileName = Path.GetFileName(filePath);
            files.Add(new ListItem(fileName, fileName)); 
        }
        Repeater1.DataSource = files;
        Repeater1.DataBind();
    }
}

Upvotes: 1

Related Questions