0

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?

2

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.