In a browser that supports HTML5, you can use the FileReader object to read a file from hdd users as a base64 encoded string. You can use this base64 view with css to show a preview. In older browsers, you will need flash or similar plugin-based code for this.
Here is an example of HTML5 that works in all modern browsers:
<html> <head> <script> var elmFileUpload = document.getElementById('file-upload'); function onFileUploadChange(e) { var file = e.target.files[0]; var fr = new FileReader(); fr.onload = onFileReaderLoad; fr.readAsDataURL(file); } function onFileReaderLoad(e) { var bgStyle = "url('" +e.target.result + "')"; elmFileUpload.parentElement.style.background = bgStyle; }; elmFileUpload.addEventListener('change',onFileUploadChange,false); </script> </head> <body> <input type="file" id="file-upload"/> </body> </html>
See the fiddle here
Martin jespersen
source share