问题
okay so I've seen many examples and questions on using readAsDataURL(), but none of them seem to resolve my issue. Following is my code :
$(document).ready(function(){
var fileReader = new FileReader();
$("form").submit(function(e){
e.preventDefault();
console.log(fileReader.readAsDataURL(document.getElementById("userfile").files[0]));
});
});
what i get in console is undefined
. I'm trying to get the base64 encoded file data on a variable so that i can upload it using ajax. Can anyone tell me what i am doing wrong?
回答1:
Most methods of a FileReader instance report the results asynchronously.
You have to bind an onload
event to capture the result:
var fileReader = new FileReader();
fileReader.onload = function(event) {
console.log(event.target.result);
};
fileReader.readAsDataURL(document.getElementById("userfile").files[0]);
来源:https://stackoverflow.com/questions/15998610/how-to-assign-value-of-readasdataurl-to-a-variable