Before HTML5, there is no easy way to read files from you local hard drives in the browser because reading files exposes security issues. Long time ago, you might be able to read files using ActiveXObject in Microsoft Internet Browser (e.g. IE6.0) but now IE is gone with the wind nowadays.
The users may want to select a local image, preview it in the browser before uploading it to the server. The users may want to do the thumbnail/cropping faster without uploading to the server. With HTML5 FileReader, all these are possible without having a server to interact.
First, you would need to check if your browser supports this, the following Javascript code checks a few objects/properties:
1 2 3 4 5 | if (window.File && window.FileReader && window.FileList && window.Blob) { // Great success! All the File APIs are supported. } else { alert('Sorry, you need HTML5 browsers!'); } |
if (window.File && window.FileReader && window.FileList && window.Blob) { // Great success! All the File APIs are supported. } else { alert('Sorry, you need HTML5 browsers!'); }
Then you would need to allow users selecting local files. We need to define a HTML file container:
1 | <input type="file" accept="*" name="upload_file" id="upload_file" /> |
<input type="file" accept="*" name="upload_file" id="upload_file" />
Then, with the following Javascript, we can easily process the file after the file is loaded at event onload.
1 2 3 4 5 6 7 8 9 | var r = new FileReader(); var file = document.getElementById('upload_file').files[0]; r.onload = function() { // we have the file data alert('file size = ' + r.result.length); // data is in r.result process(r.result); } r.readAsDataURL(file); // read as BASE64 format |
var r = new FileReader(); var file = document.getElementById('upload_file').files[0]; r.onload = function() { // we have the file data alert('file size = ' + r.result.length); // data is in r.result process(r.result); } r.readAsDataURL(file); // read as BASE64 format
You can read as BASE64 format using readAsDataURL. Alternatively, you can readAsText().
Security Issues
Note that you can’t read the file actual path in your code because it is considered insecure to expose the real path, therefore all you will get is a fake path like C:\fakepath\yourfile.txt. And also you can’t give the real file path except via the HTML file selector, which is considered secure because users have to manually select the files he/she knows clearly what he/she is doing!
Demo/Example
You can visit this page, which provides a local file BASE64 converter.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: How to Allow Images Instead of URL in WordPress Comments?
Next Post: C++ Coding Exericse - Tiny TimeIt Utility to Time the Applications