2

I have the following HTML markup:

<div>
  <a>browse<input type="file" name="annex"></a>
  <span class="filename"></span>
</div>

I am using this markup to style the file input with CSS.

I would like to show the file name (filename.ext) in the span with class "filename".

I tried the following with JQuery:

$('.file').on('file', function (event, files, label) {
  $('.path').html($(this).val().replace(/\\/g, '/').replace(/.*\//, ''));
  alert($(this).val());
});

The span is still empty and the alert result is also empty.

How can I do this?

Thank You, Miguel

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

3 Answers3

2

Try this:

$('input[type="file"]').on('change', function (event, files, label) {
    var file_name = this.value.replace(/\\/g, '/').replace(/.*\//, '')
    $('.filename').text(file_name);
});

Demo here

Sergio
  • 28,539
  • 11
  • 85
  • 132
0

This is not possible with JavaScript, as it is considered insecure for the script to read your local file paths.

However, if you're creating an HTML5 site, you might be luckier with the HTML5 File API.

Also, you might want to check this interesting link over here.....

Zathrus Writer
  • 4,311
  • 5
  • 27
  • 50
0

You can read it, but you can't set it. so it won't have a value until you click on it and pick a file.

Even then, the value will likely be mangled with something like c:\fakepath\ to keep the details of the user's filesystem private.

Reference Can't get value of input type="file"?

Try out this link Get filename from input [type='file'] using jQuery

Community
  • 1
  • 1
Vaibs_Cool
  • 6,126
  • 5
  • 28
  • 61