reza
reza

Reputation: 6358

How to retrieve the selected filename using angular?

I am using the following code to display a file selection dialog in an angular application and I'm not sure how to retrieve the selected filename.

<label class="btn btn-default">
    Import
    <input type="file"
           change="change()" hidden>
</label>

Is there a recommended way to do this?

Upvotes: 0

Views: 504

Answers (2)

reza
reza

Reputation: 6358

it turns out what I was missing, I failed to mention it was that this is an angular application. To get to the selected file, I had to change to

                <label class="btn btn-default">
                Import
                <input type="file"
                       (change)="change($event)" hidden>
            </label>

then in the function, the selected filename is in event.target.files[0].name.

    public change($event): void {
    let that = this;
    let files = $event.target.files;
}

thank you all for the responses.

Upvotes: 1

Kristian
Kristian

Reputation: 501

First, pass event reference into input change:

<input type="file" change="change( e )" hidden> 

Second, retrieve the name from event target:

function change( e ) {
      const files = e.target.files;
      const file = files[0];
      const file_name = file.name;
}

Read some docs on input file. Such as this @Mozilla.

NOTE:

If you have troubles with the onchange event, assign some id to your input, perhaps like this:

<input type="file" id="file_input">

and then query for the element by that id, like this:

document.getElementById('file_input').onchange = function( e ) {
      const files = e.target.files;
      const file = files[0];
      const file_name = file.name;
      alert(file_name);
}

Upvotes: 1

Related Questions