how to assign value of readAsDataURL() to a variable?

会有一股神秘感。 提交于 2020-01-04 06:04:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!