How to get the filename from the Javascript FileReader?

前端 未结 3 1595
一整个雨季
一整个雨季 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 10:54

    I got the filename and filesize through the FileReader this way

    First of all, the reader is a javascript FILE API specification that is so useful to read files from disc.

    In your example the file is readed by readAsDataURL.

    reader.readAsDataURL(this.documentFile);
    var name = this.documentFile.name;
    var size = this.documentFile.size;
    

    I tried on my site where use this.files[0] instead and worked fine to catch the name and the size with jQuery into an input element.

     reader.readAsDataURL(this.files[0]);
     $("#nombre").val(this.files[0].name);
     $("#tamano").val(this.files[0].size);
    
    0 讨论(0)
  • 2020-12-10 11:07

    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.

    0 讨论(0)
  • 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');
    
    0 讨论(0)
提交回复
热议问题