How to get the filename from the Javascript FileRe

2019-04-03 11:11发布

I'm using the Javascript FileReader to load an image in the browser:

e = e.originalEvent;
e.dataTransfer.dropEffect = 'copy';
this.documentFile = e.dataTransfer.files[0];

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

This works fine. I now want to get the original filename of the image, but I've got no clue how and looking around the internet I can't find anything either?

Does anybody know how I can get the filename through the FileReader? All tips are welcome!

2条回答
可以哭但决不认输i
2楼-- · 2019-04-03 11:55

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');
查看更多
祖国的老花朵
3楼-- · 2019-04-03 12:00

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.

查看更多
登录 后发表回答