How to get Image Preview after browsing through fileupload control using JavaScript

There are situations when you work with File Upload controls and you want to show the image preview when you hit ok in the dialog box. There are many solution but we are going to demonstrate using JavaScript. Now the below code snippet uses showImage function which first splits the complete path present in file upload text box. Later it appends 'file:///' to the complete file path.

Example:



function showImage(id,img,divName,no)
{
var fileUploader = id.value;            
dots = fileUploader.split(".");

//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];
if(fileType=='.jpg'||fileType=='.JPG'||fileType=='.gif'||fileType=='.GIF' ||fileType=='.jpeg'||fileType=='.JPEG'||fileType=='.bmp'||fileType=='.BMP'||       fileType=='.png'||fileType=='.PNG'||fileType=='.tif'||fileType=='.TIF'||fileType=='.thm'||fileType=='.THM')
{
// alert('That file is OK!');
// return true;
}
else
{
return false;
}

var filePath = fileUploader.split("\\"); 
var path = 'file:///';
for(var i = 1; i <  filePath.length;i++)
{
path += filePath[i];
if(i != filePath.length -1)
path += "/";
}  
if(path.length > 1)
{
if(no==1)
{                   
var ele= document.getElementById('<%= panellogo.ClientID %>');
ele.style.display = 'block';
var ele1= document.getElementById('<%= imglogo.ClientID %>');           
}
else if(no==2)
{
var ele= document.getElementById('<%= panelheader.ClientID %>');
ele.style.display = 'block';
var ele1= document.getElementById('<%= imgheader.ClientID %>');              
}
else if(no==3)
{
var ele= document.getElementById('<%= panelfooter.ClientID %>');
ele.style.display = 'block';
var ele1= document.getElementById('<%= imgfooter.ClientID %>');
}
else if(no==4)
{
var ele= document.getElementById('<%= panelmiddlebar.ClientID %>');
ele.style.display = 'block';
var ele1= document.getElementById('<%= imgmiddlebar.ClientID %>');           
}
ele1.src =path ; 
}
}

0 comments:

Post a Comment

 

About Me

It's Me!Hi, I'm Moinuddin. I'm a Software Engineer at WIPRO working on Microsoft .NET Technology. I'm interested in a wide range of technology topics, mainly Microsoft including Windows Azure, WCF, WPF, Silverlight and any other cool technology that catches the eye.

Site Info

ProjectCSharp.com is mainly about demonstrating real time examples in different technologies like ASP.NET, WCF, WPF, Silverlight, Azure etc..,

Followers

Help Links

Project CSharp (C#) Copyright © 2011. All Rights Reserved.