Converting image to binary array (blob) with HTML5
I am trying to use the 'FileReader' and 'File' APIs that are supported in HTML5 in Chrome and Firefox to convert an image to a binary array, but it does not seem to be working correctly on Chrome. I just have a simple HTML page with a file as the input type:
<input id="image_upload" type="file" />
And from here I am using jQuery to grab the contents of the image and then using the API: File.getAsBinary()
to convert it to a binary array. This works perfectly on Firefox but not on Chrome:
$('#image_upload').change(function() {
var fileList = this.files;
var file = fileList[0];
var data = file.getAsBinary();
//do something with binary
});
When this method executes on Chrome I get an error in the console saying:
uncaught TypeError: Object #<File> has no method 'getAsBinary'
I am using the most up-to-date version of Google Chrome which as of today (2011-05-31) is version: 11.0.696.71 and according to sources this method is supposed to be supported with the most current version of Chrome.
That did not seem to work so I tried to use the FileReader
API and did not have any luck with that either. I tried doing this to no avail:
$('#image_upload').change(function() {
var fileList = this.files;
var file = fileList[0];
var r = new FileReader();
r.readAsBinaryString(file);
alert(r.result);
]);
But that only returns nothing which I assume i开发者_如何学编程s because readAsBinaryString()
is a void method. I am at a complete loss of how to get this working for both Chrome and Firefox. I have searched all over the web looking at countless examples to no avail. How can I get it working?
The FileReader API is an asynchronous API, so you need to do something like this instead:
var r = new FileReader();
r.onload = function(){ alert(r.result); };
r.readAsBinaryString(file);
Figured out I could go pass a call back to myself such as:
create_blob(file, function(blob_string) { alert(blob_string) });
function create_blob(file, callback) {
var reader = new FileReader();
reader.onload = function() { callback(reader.result) };
reader.readAsDataURL(file);
}
This works perfectly. I am able to pass the blob returned from the onload function to myself once it is finished.
精彩评论