Oct 19, 2011

How to display Image in Repeater Control from folder?

Download full project
 
Recently I was working on a project where I needed to dispaly an images into Repeater control from Folder. So I thought let me create a blog post for that and share it with my reader.
It is very simple to display an image into repeater control from folder just like below.
In this project  I have used one file upload control from where we are uploading images to one specific folder and then display all the uploaded images to the repeater control using an array.

Here is html code for  .aspx page
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
    #lblErrorMessage{color:#FF0000;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblErrorMessage" runat="server" EnableViewState="false"></asp:Label>
        <asp:FileUpload ID="fuUpload" runat="server" />
        <br />
        <asp:Button ID="btnFileUpload" runat="server" Text="Upload File" 
            onclick="btnFileUpload_Click" />
    </div>
    <div>
        <asp:Repeater ID="rptImage" runat="server" Visible = "true">
            <ItemTemplate >
                    <img ID="imgLeft" runat="server" src='<%# Container.DataItem %>' alt='' style="height:100px;width:100px;" />
            </ItemTemplate>
        </asp:Repeater>
    </div>   
    </form>
</body>
</html>

Here code sample is explained in small peices.

    Page Load Event
    In page load event just calling a bindImages which will find all the images from folder and then bind it to the Repeater.
   
    string folderPath = "images/";
    protected void Page_Load(object sender, EventArgs e)
    {
        BindImages(folderPath);
    }

//bindImages Function
In below function we are getting all the images to the string array then loop through it and get the file name from whole path and concat it with folder path and again assign it to array element. Once all the image path changed then bind an file path array to the Repeater.

 public void BindImages(string folderPath)
    {
        //get all the files from flder
        string[] strImgs = System.IO.Directory.GetFiles(Server.MapPath(folderPath));
        //Loop through all the file and get only file name and concat it with folder name
        for (int count = 0; count < strImgs.Length; count++)
        {
            string filePath = strImgs[count];
            filePath = filePath.Substring(filePath.LastIndexOf('\\')+1);
            string newFilePath = folderPath + filePath;
            strImgs[count] = newFilePath;
        }
        // Bind an image file name to repeater.
        rptImage.DataSource = strImgs;
        rptImage.DataBind();
    }

When save button clicked then this code will check that file is selected or not, based upon file selected it will take an action.

 //Before procceding check that user has select file
 
        if (fuUpload.HasFile)
        {
            //Call save File method
            SaveUploadedFile(fuUpload.PostedFile);
            BindImages(folderPath);
        }
        else
        {
            // Notify user that file is not selected
            lblErrorMessage.Text = "Please select a file to upload.";
        } 
 
        Code for SaveUploadedFile function
below code will create a folder path to save image to the disk then check that the file name is exist in target folder if yes then it will contact counter number at begining of the file name and again check for duplicate file name, once file name found then it will save image with that file name on the disk.
     
    void SaveUploadedFile(HttpPostedFile file)
    {
        // Secify the path to save file.
        string savePath = Server.MapPath("Images/");
        // Get the name of the file to upload.
        string fileName = fuUpload.FileName;
        string pathToCheck = savePath + fileName;
        string tempfileName = "";
        // Check at target that file is exist with same name then change filename while saving
        if (System.IO.File.Exists(pathToCheck))
        {
            int counter = 1;
            while (System.IO.File.Exists(pathToCheck))
            {
                tempfileName = counter.ToString() + fileName;
                pathToCheck = savePath + tempfileName;
                counter++;
            }
            fileName = tempfileName;
        }
        else
        {
            lblErrorMessage.Text = "Your file was uploaded successfully.";
        }
        savePath += fileName.Replace(" ","");
        //save uploaded file to disk
        fuUpload.SaveAs(savePath);
    }

 Here I have uploaded full project code for the reference. You can download it from the top


Output:



2 comments:

Anonymous

very nice one how about VB sample i was seriosly looking for this!

Noor Rahman

Thanks !nice work how can i add the delete button with each image .Thanks in advance

Post a Comment

Author Profile

Total Pageviews

Categories

Followers

 
Top Programming   Sites Technology Top Blogs Technology blogs Technology Blogs

Sponsors