How to get the filename from the Javascript FileReader?

妖精的绣舞 提交于 2019-11-30 11:05:41

This is prob not the best solution, BUT it worked for me.

var reader = new FileReader();
reader.fileName = file.name // file came from a input file element. file = el.files[0];
reader.onload = function(readerEvt) {
    console.log(readerEvt.target.fileName);
};

Not the best answer, but a working one.

If you want the filename to a variable:

var filename;
var reader = new FileReader();
reader.onloadend = function () {
    if (reader.result) {
        console.log(reader);
        $('#theImage').attr('src', reader.result);
        filename = reader.result;
    }
};
reader.readAsDataURL(this.documentFile);

If you want it to run in a function:

var reader = new FileReader();
reader.onloadend = function () {
    if (reader.result) {
        console.log(reader);
        $('#theImage').attr('src', reader.result);
        myfunctionafter(reader.result);
    }
};
reader.readAsDataURL(this.documentFile);

If you want to get the info out inside another function:

var reader = new FileReader();
var filename = reader.onloadend = function () {
    if (reader.result) {
        console.log(reader);
        $('#theImage').attr('src', reader.result);
        return reader.result;
    }
};
reader.readAsDataURL(this.documentFile);

There might be a problem when your reader.onloadend might finish before the function you are running it from. Then you should do two functions and trigger the myfunctionafter(reader.result); from inside

Or you could simply get the src after

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