Thursday, 30 May 2013

How to use File upload control and show images in Image control



How to use File upload control and show images in Image control


Step 1 : First create your website in asp.net and create one .aspx page .

Step2: Open .aspx page and add Fileupload control .

<asp:FileUpload ID="FileUpload1" runat="server" />

Step 3 : And add button control to upload fileupload images.

<asp:Button ID="BtnSubmit" runat="server" Text="Submit Image" OnClick="BtnSubmit_Click" />

Step 4 :Add image control to show uploaded image on page.

<asp:Image ID="Image1" runat="server"  />

Step 5:  Add Server side code to access image upload transaction.

protected void BtnSubmit_Click(object sender, EventArgs e)
    {
        //check is FileUpload contol selected any item or not
        if (FileUpload1.HasFile)
        {
            FileUpload1.SaveAs(Server.MapPath("~/images/" + FileUpload1.FileName));
            Image1.ImageUrl = "~/images/" + FileUpload1.FileName;
        }
    }

Step 6 : Just your page and try to upload files and view uploded image on page.

//-----------------------  Page Design Code -----------------

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUploadControl.aspx.cs" Inherits="FileUploadControl" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <br />
            <asp:FileUpload ID="FileUpload1" runat="server" />

            <br />
            Select only images
            <br />

            <asp:Button ID="BtnSubmit" runat="server" Text="Submit Image" OnClick="BtnSubmit_Click" />

            <br />

            <br />

            <asp:Image ID="Image1" runat="server"  />
        </div>
    </form>
</body>
</html>

//-----------------------  Page Server Side Code -----------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class FileUploadControl : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void BtnSubmit_Click(object sender, EventArgs e)
    {
        //check is FileUpload contol selected any item or not
        if (FileUpload1.HasFile)
        {
            FileUpload1.SaveAs(Server.MapPath("~/images/" + FileUpload1.FileName));
            Image1.ImageUrl = "~/images/" + FileUpload1.FileName;
        }
    }
}

No comments:

Post a Comment

Thank you for your interest .