Monday, 4 June 2012

Upload an image on server in ASP.Net through ajax

Test.aspx
<form id="frmUploadImageFile" name="frmUploadImageFile" action="UploadFile.aspx" enctype="multipart/form-data" method="post" >           
<input id="flImage" name="flImageName" type="file" />
<input type="submit" name="btnUpload" value="Upload Image" />           
</form>      

<img id="imgPreview" alt="" src="" />


<script type="text/javascript">
        di_jq(document).ready(function () {

            di_jq('#frmUploadImageFile').ajaxForm({
                success: function (response) {
                    if (response == "No File") {
                        alert("Please browse an image file.");
                    }
                    else {
                        di_jq("#imgPreview").attr("src", response);
                    }
                }

            });
        });
</script>

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

Default.aspx.cs
using System.IO;

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Files.Count > 0)
        {           
if (!string.IsNullOrEmpty(Request.Files.AllKeys[0]) && ((Request.Files.AllKeys[0] == " flImageName") || (Request.Files.AllKeys[0] == " flImageName")))
            {
                     this.HandleUploadedImageFile();
            }              

        }
    }

private void HandleUploadedImageFile()
    {
        string ImagesPath = string.Empty;
        string FileName = string.Empty;
        string SaveFilePath = string.Empty;
        string FilePathUrl = string.Empty;

        try
        {
            ImagesPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, Images”);

            if (Request.Files[0].InputStream.Length > 0)
            {
                if (!(Directory.Exists(ImagesPath)))
                {
                    Directory.CreateDirectory(ImagesPath);
                }
                if (!string.IsNullOrEmpty(Request.Files.AllKeys[0]) && ((Request.Files.AllKeys[0] == "flImageName") || (Request.Files.AllKeys[0] == "flImageName")))
                {
                    FileName = "Image_" + Guid.NewGuid().ToString() + ".png";
                }

                SaveFilePath = Path.Combine(ImagesPath, FileName);

                Request.Files[0].SaveAs(SaveFilePath);

                FilePathUrl = HttpContext.Current.Request.Url
 + "/" + “Images/” + FileName;

                Response.Write(FilePathUrl);
            }
            else
            {
                Response.Write("No File");
            }

        }
        catch (Exception)
        {

        }
    } 

No comments:

Post a Comment