Home     RSSRSS

Posts Tagged ‘HTML5’

HTML 5 Image Preview with File API’s

December 17, 2011 by kiranbadi1991 | Comments Off on HTML 5 Image Preview with File API’s | Filed in Browser, Development

I have been working for sometime now on HTML5 with Image preview and upload functionality.Sometimes back I had tried to implement the image preview functionality on the client side using the JavaScript without HTML5 and had been having really hard time making the code work across all browser without tweaking the browser setting on the client side.I would say its impossible without a some kind of flash plugin or java applet to implement this functionality given that lot of browsers just blocks the script access to the input file src tag unless someone is extremely intelligent programmer.I had written about this earlier over here.Finally I gave up that approach and decided to have graceful fallback approach using both HTML5 and input file type by using the object detection feature of the browser.

HTML 5 has somewhat cool features when it comes to File API.With File API’s we can now have all the information as what is required to make the File preview functionality complete.Using HTML5 File Api,one can easily know the file name,file size and if required the file last modified date as well.Below is the rough code,which will give you some ideas as how to preview the image before uploading it in the server,

<!DOCTYPE HTML>
<html>
<head>
<meta charset=”utf-8″>
<script type=”text/javascript”src=”js/checkbrowser_01.js”>

</script>
<title>HTML 5 Image Preview</title>
</head>
<body>
<label>Upload your Image:</label>
<input name=”imguploader” type=”file” multiple=”” accept=”image/jpeg”

id=”idimgup” title=”Imageuploader” onChange=”previewimage1()”/>
<br></br>
<input name=”Submit” type=”button” class=”clbtnpreview” id=”idbtnpreview”

title=”Preview” onClick=”previewimage()” value=”Preview”/><br></br>
<div>
<img name=”DemoImage” src=”” id=”idimg” width=”400″ height=”400″

alt=”Demo Image” style=”background-color: #00FFFF”/>
</div>
</body>
</html>

In the above code,checkbrowser js file has below function which will take the image path and show it for preview by reading data as dataURL of the file reader interface.

imgreader = new FileReader();
imgreader.onload=function(Event){
document.getElementById(“idimg”).src = Event.target.result;
};
function previewimage1(){
if (document.getElementById(“idimgup”).files.length === 0)

{return; }
var File = document.getElementById(“idimgup”).files[0];
imgreader.readAsDataURL(File);
}

If you are using the F12 Developer tools of the browser ,we can clearly see the image path appended to the src of the image using the base 64 encoding.Using this approach one can easily preview the images on any HTML5 File API compliant browsers.

In addition to using FileReader interface for previewing images, we also have a choice of

using createObjectURL method for previewing the images.The code for windows create object URL looks like below,

<!DOCTYPE html>
<html>
<head>
<title>HTML 5 Image Preview Sample</title>
<meta http-equiv=”X-UA-Compatible” content=”IE=9″>
<style type=”text/css”>
span{
align:left;
}
</style>
</head>
<body>
<h1>HTML 5 Image Preview Sample</h1>
<input type=”file” id=”fileSelector” multiple accept=”image/*” />

<div id=”fileContentList” style=”list-style-type: inline-block;”><

br></br></div>

<!– This will be populated with <img> elements via JavaScript. –>
<script type=”text/javascript”>
var infomessage = [];
if (!document.getElementById(‘fileSelector’).files) {
message = ‘<p>The ‘ +
<a href=”http://dev.w3.org/2006/webapi/FileAPI/” target=”_blank”>

File API</a>s ‘ +
‘are not fully supported by this browser.</p>’ +
‘<p>Upgrade your browser to the latest version.</p>’;
document.querySelector(‘body’).innerHTML = infomessage;
}
else {
document.getElementById(‘fileSelector’).addEventListener(‘change’,

handleFileSelection, false);

// Add an onchange event listener for the <input id=”fileSelector”> element.
}
function handleFileSelection(evt) {

var files = evt.target.files; //The files selected by the user
if (!files) {
alert(“<p>At least one selected file is invalid – do not select any folders.</p);
return;
}
// The variable “files” is an array of file objects.
for (var i = 0, file; file = files[i]; i++) {
window.URL = window.URL || window.webkitURL;
var img_element = document.createElement(‘img’); // Select Image file only.
img_element.src = window.URL.createObjectURL(file);.
img_element.width = 400; // Make all images the same width.
img_element.height= 400;// Make all images the same height
img_element.style.verticalAlign = “middle”; //

img_element.style.margin = “4px 4px 4px 0”;

// The file URL is not needed once the file image has been fully loaded.
img_element.onload = function() {

window.URL.revokeObjectURL(this.src);

}
var span_element = document.createElement(‘span’);
span_element.innerHTML = file.name;
var li_element = document.createElement(‘li’);
li_element.style.display= “inline”;
li_element.appendChild(img_element);
li_element.appendChild(span_element);
document.getElementById(‘fileContentList’).appendChild(li_element);
} // for
} // handleFileSelection
</script>
</body>
</html>

If you are using createObjectURL method, then you need to make sure that you account for both windows and webkit objects by using the below code.

window.URL = window.URL || window.webkitURL;

However for some reasons,using the createObjectURL method was not working in Safari 5x and Opera 11x. With Opera 11.60/Safari 5.1(on windows 7) I can see in Dragon Fly/developer’s tools, that opera for some reasons do not identify the window.createURL as an Object and gives you type reference error.So this makes me believe that these 2 browsers has got somewhat partial support for file api though they both claim to support HTML5 file api’s completely.

There is one thing which I noticed while working with both the above codes, from the time I upload the image to the time browser displays the image for rendering, I can feel somewhat pause which was not the case earlier when I did not use HTML5 File API.Seems like I have a bias here.

Overall its good stuff and definitely a step which can enhance the speed of the web and websites.

Technorati Tags: HTML5,FileReader,createObjectURL,ImagePreview.

Tags: , ,

Browser’s Feature check for HTML 5 File API’s

December 11, 2011 by kiranbadi1991 | Comments Off on Browser’s Feature check for HTML 5 File API’s | Filed in Browser, Scripting

Sometimes it becomes necessary that we check in the browser for its capability in supporting some features.While playing around with HTML5 File API’s I thought of  the below code for checking if the browser supports HTML5 File API.I have tested it in safari 5.1.2/IE 9.0 /FF 8.0 and Chrome 15.0x , it works perfectly and displays the information as what is required.

function checkforhtml5fileapi(){

  alert("Function works");
    
if (!document.getElementById('input file type element id').files) {
       
     alert(" Browser do not support HTML 5 File API Spec");
 
      }
          else {
        
     alert(" Browser supports HTML 5 File API Spec");
         
      }
   
     }

Tags: ,

HTML Input Type File Browse Element /FakePath Mystery and Plain Stupid W3C Specification.

November 11, 2011 by kiranbadi1991 | 3 Comments | Filed in Browser, Development, Performance Engineering

From past couple of days I have been working on the piece of code where I have to upload and Preview the image.All upload and preview I wanted it to be on the same page at client side with no server calls happening for previewing the image other than doing a submit.

I was thinking it would be simple stuff where I have a simple HTML Page which will have Input File type element tag which comes with Browse button to pick the file from the desktop and attach the file path to the IMG Element SRC and preview it in the same page for the users.My bad though the logic looks so perfect and  simple, yet its implementation is impossible, given that for the sake of security(Google/Bing/Yahoo Search Says so), all browsers under normal circumstances or in default mode puts the severe restriction on the input type file element capability.Unless we tweak setting in browsers, its not going to display Images with this logic and some browsers just plainly refuse to display it no matter what.

Here is code I wrote so as to upload and preview the image on the same page.Please note that this rough cut of the code and it can altered or changed to fit in the dimensions of the image in the browsers where it works.I have not validated this code for w3c validation.

   1:  <!DOCTYPE HTML>
   2:  
   3:  <html dir="ltr" lang="en-US">
   4:  
   5:  <head>
   6:  
   7:  <title>Image upload trial</title>
   8:  
   9:  <style type="text/css">
  10:  
  11:  div.clmaincontainer{
  12:  
  13:    width:30%;
  14:  
  15:    height:600px;
  16:  
  17:    border-style:solid;
  18:  
  19:    }
  20:  
  21:  div.climg{
  22:  
  23:  width:30%;
  24:  
  25:  height:auto;
  26:  
  27:  border-style:inset;
  28:  
  29:  }
  30:  
  31:  </style>
  32:  
  33:  <meta charset="utf-8">
  34:  </head>
  35:  
  36:  <body>
  37:  
  38:  <div id="idmaincontainer" class="clmaincontainer">
  39:  
  40: <input type="file" name="img" id="idimgupload" class="climgupload">
  41:  
  42:  <img src="#" id="my_img" class="climg " alt="Image"/>
  43:  
  44:  <div id="idimgdisplay" class="climgdisplay"></div>
  45:  
  46:  </div>
  47:  
  48:  <script src="./1.5/jquery.min.js"></script>
  49:  
  50:  <script>
  51:  
  52:  $(document).ready(function(){
  53:  
  54:                  $('#idimgupload').change(function(){
  55:  
  56:                  var path = $('#idimgupload').val();
  57:  
  58:                  path = path.replace("C:\\fakepath\\", "");
  59:  
  60:                   alert(path);
  61:  
  62:                  $('#my_img').attr('src',path );
  63:  
  64:                                 alert("test for bind");
  65:  
  66:                                  });
  67:  
  68:  });
  69:  
  70:    </script>
  71:  </body>
  72:  </html>

Now lets start with Microsoft IE, I have been fan of Microsoft for number of years and for various good reasons.One among them is the way they share information about their products via blogs/MSDN/Articles etc.In fact I can go ahead and say that some of best things I have learned is from Microsoft Folks who are in Development/Support/.Net Reverse Engineering/IIS/IE teams etc.

Okay now coming back to this topic,this piece of code works perfectly fine in IE9,IE8,IE7 version of browsers provided we tweak some setting in IE. I have tested it and can see that right after we select the Image file, it displays your image.The setting which one needs to do is

  • Add your site in the IE’s Trusted Site list.
  • Enable the below Setting in IE.Click Tools Bar in IE.Select Internet Options >Security >Custom Level.If you scroll the list of options to enable or disable over there, you should see below option.Enable this option.

Include local directory path when uploading files to a server

Now coming for Firefox/Safari/Google Chrome all latest version at the time of this writing, I can only say that there is some magic happening in Firefox browser,sometimes it works and other times it does not work.But this piece of code surely do not work on Safari/Google Chrome and we get below Fake path message,

 

image

 

image

 

Both Chrome and Safari adds the fake path to the actual directory structure in the alert box and in reality looks for the image in the root folder of the application on the  server.So this solution fails with 404 error when viewed via browser developer tools(F12 tools).I can see this in DOM that filename is replaced correctly but path of the file is set to the root of the folder.So basically path is as http://localhost:7000/D3.jpeg

Ok now why do the browser are behaving like this with the element which they wholeheartedly support,below I feel is the reasons for this,

http://www.w3.org/TR/html5/number-state.html#file-upload-state

I am not sure as what security holes they are seeing here,of course I am not a hard core expert in programming,but I also know there are very very few guys who can really hack the stuff,but again we should not forget that now a days security companies are coming up with products which blocks just anything and everything if they suspect.Now with  so much intelligence around,does it make sense to ignore this solution ?

For every image that is uploaded in the web and previewed in the web,it makes at least 2 calls to the server,one for storing the image to some temp location and other to retrieve the image to preview it.What a waste of bandwidth and money here.

I am also not getting where are client side web performance experts,don’t they see the benefits of this element and changes it can bring to the web once these silly restriction are removed or are they saying that risks outweighs the benefits here ?..

Update: Here is the link for IE which talks about workaround to this issue.

http://msdn.microsoft.com/en-us/library/ms535128(VS.85).aspx

Tags: , , ,