Tuesday, October 9, 2012

Asynchronous File UploadControl To Display Thumbnail Images After Uploading

Previously in This Post Showed how to use Asynchronous File UploadControl to upload images.
Now i will show how to display the uploaded Image in Thumbnail.

OutPut :




First add a folder as scripts and add latest jquery.js and jquery.json.js files in the created folder.
Now drag and drop the above two files on to Default.aspx page within the header tag.
Reference links are created after drag and drop.
Now write the scrip after the reference links are created
The Script looks as below




<head runat="server">
         <title></title>
    <script src="scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
    <script src="scripts/jquery.json-2.3.min.js" type="text/javascript"></script>

<script type="text/javascript">
    function uploadComplete() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/ShowImage",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: OnReturn
        });
        function OnReturn(response) {            
            $('#imgPreview').attr('src', response.d);
        }
    }
    function uploadError() {
        $get("<%=lblstatus.ClientID%>").innerHTML = "File upload Failed.";
    }
    function uploadStarted() {
        $get("<%=lblstatus.ClientID%>").innerHTML = "File upload started.";
    }
    </script>

</head>

Code Behind :


    public partial class Default : System.Web.UI.Page
    {
        static string url;
        protected void Page_Load(object sender, EventArgs e)
        {
        }
 
        protected void FileUploadComplete(object sender, EventArgs e)
        {           
            if (AsyncFileUpload1.HasFile)
            {
                string strPath = MapPath("~/UploadedImages/") + 
                           Path.GetFileName(AsyncFileUpload1.FileName);
                AsyncFileUpload1.SaveAs(strPath);
                url = "/UploadedImages/" + Path.GetFileName(AsyncFileUpload1.FileName);
                Session["url"] = "/UploadedImages/" 
Path.GetFileName(AsyncFileUpload1.FileName);                
            }
        }
 
        [WebMethod]
        public static string ShowImage()
        {
            string img = "";
            if (url != null)
                img = url;
            else
                img = "images/default.jpg";
            return img;
        }
    }

No comments:

Post a Comment