mOxie Library
I found a library capable of doing what you are asking for.
This is a polyfill listed in GitHub of the modernizr called mOxie .
The library is fantastic except to start development. I had to compile it, then start testing ... then I fixed some compilation errors, and some errors in the generated JavaScript, then it finally worked.
I used the following parts of mOxie:
-
FileInput : component that allows you to select a file and use the files that are selected using a
FileReader
-
FileReader : read a file
-
Image : allows you to manipulate images, such as resizing it
For the difficulty I had in compiling, I decided to create a repository in GitHub with the already compiled version:
Example of use
I put in the folder \v1.2.1\samples
, the example of how to do what you said:
-
image-preview-before-upload.htm
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="moxie.min.js"></script>
<script>mOxie.Env.swf_url = 'Moxie.swf';</script>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new mOxie.FileReader();
reader.onload = function (e) {
var img = new mOxie.Image();
img.onload = function() {
img.downsize({width:100});
var tgt = document.getElementById("target");
img.embed(tgt);
};
img.load(e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</head>
<body>
<form id="form1">
<div id="container">
<a id="file-picker" href="javascript:;">Browse...</a>
</div>
<script>
var fileInput = new mOxie.FileInput({
browse_button: 'file-picker', // or document.getElementById('file-picker')
container: 'container',
accept: [
{title: "Image files", extensions: "jpg,gif,png"} // accept only images
],
multiple: true // allow multiple file selection
});
fileInput.onchange = function(e) {
// do something to files array
//console.info(e.target.files); // or this.files or fileInput.files
readURL(this);
};
fileInput.init(); // initialize
</script>
<div id="target"></div>
</form>
</body></html>
Compatibility
It works on IE8 andIE9. Also in Chrome ,FireFox and Opera .
I had trouble with Safari ,IE6 and IE7 .
Maybeit'sbesttouseaselectiveapproachbetweenmyanswer,yourowncode(shouldworkinSafari),and @CarlosMartins answer (which uses AlphaImageLoader, so I researched it in IE6 and IE7). You could use conditional comments to achieve full compatibility if you want.
Dependencies
To work in IE8 and IE9, mOxie requires either Flash or SilverLight . It looks like they have plans to support the use of Java as well, but for now it does not.