Wednesday, August 27, 2014

File Upload

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <center>
            <fieldset style="width: 25%">
                <legend>Uplaod and Preview the Image</legend>
                <table>
                    <tr>
                        <td>
                            Upload Image:
                        </td>
                        <td>
                            <asp:FileUpload ID="FileUpload1" runat="server" /><br />
                            <asp:Label ID="lblmessage" runat="server"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td>
                            <asp:Button ID="btnupload" runat="server" Text="Upload Image" OnClick="btnupload_Click" />
                        </td>
                    </tr>
                </table>
                <asp:Image ID="imgpreview" runat="server" Width="350px" Height="300px" />
            </fieldset>
        </center>
    </div>
    </form>
</body>
</html>

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

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

    }
    protected void btnupload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string path = Server.MapPath("~/images/") + FileUpload1.FileName;
            FileUpload1.SaveAs(path);
            imgpreview.ImageUrl = "~/images/" + FileUpload1.FileName;


        }
        else
        {
            lblmessage.Text = "Upload images";
            imgpreview.ImageUrl = "";

        }
    }
}