Javascript language

adplus-dvertising
Image Upload Control
Previous Home Next

How to use Image Upload control in JavaScript

Step 1. Written below code in your application.

<html>
<script language="javascript">
var maxWidth=100;
var maxHeight=100;
var fileTypes=["bmp","gif","png","jpg","jpeg"];
var outImage="previewField";
var defaultPic="spacer.gif";
function preview(what){
  var source=what.value;
  var ext=source.substring(source.lastIndexOf(".")+1,source.length).toLowerCase();
  for (var i=0; i<fileTypes.length; i++) if (fileTypes[i]==ext) break;
  globalPic=new Image();
  if (i<fileTypes.length) globalPic.src=source;
  else {
    globalPic.src=defaultPic;
    alert("That is not avalid image\nPlease load an image with an 
extention of one of the following:\n\n"+fileTypes.join(", "));
  }
  setTimeout("apply_changed()",200);
}
var globalPic;
function apply_changed(){
  var field=document.getElementById(outImage);
  var x=parseInt(globalPic.width);
  var y=parseInt(globalPic.height);
  if (x>maxWidth) {
    y*=maxWidth/x;
    x=maxWidth;
  }
  if (y>maxHeight) {
    x*=maxHeight/y;
    y=maxHeight;
  }
  field.style.display=(x<1 || y<1)?"none":"";
  field.src=globalPic.src;
  field.width=x;
  field.height=y;
}
</script>
<body>
<input type="file" id="picField" onchange="preview(this)">
</body>
</html>

Step 2. Run the Application. Click on Button.

Previous Home Next