How to get the filename from the Javascript FileReader?

前端 未结 3 1608
一整个雨季
一整个雨季 2020-12-10 10:26

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

e = e.originalEvent;
e.dataTransfer.dropEffect = \'copy\';
this.documentFile = e.dataTr         


        
3条回答
  •  天涯浪人
    2020-12-10 11:08

    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');
    

提交回复
热议问题