52

I have a file upload input and when I click the browse button and select the file, I want the filename and extension to appear in two input text boxes (see code sample).

It works correctly with the extension, but the filename also shows the path which gives me the fakepath warning.

I understand why, but what's a good way to do this and just get the filename into that box. I don't need the path.

function getoutput(){
    outputfile.value=inputfile.value.split('.')[0];
    extension.value=inputfile.value.split('.')[1];}
    <input id='inputfile' type='file' name='inputfile' onChange='getoutput()'><br>
    Output Filename <input id='outputfile' type='text' name='outputfile'><br>
    Extension <input id='extension' type='text' name='extension'>
M--
  • 25,431
  • 8
  • 61
  • 93
CheeseFlavored
  • 1,922
  • 1
  • 21
  • 28
  • Sorry to highjack this, but someone deleted my answer to this thread where you said that you had just submitted an app to the App Store and got that UIWebView deprecation warning: https://stackoverflow.com/questions/57700996/flutter-how-to-fix-itms-90809-deprecated-api-usage-apple-will-stop-accepting/57705283?noredirect=1#comment101862403_57705283 I'm very curious if Apple will reject it based on the UIWebView usage. Can you please let me know? – Tonald Drump Aug 30 '19 at 08:15

10 Answers10

65

This is bit old post...just for info

   var files = event.target.files
   var filename = files[0].name
   var extension = files[0].type

In the type you will find the extension for eg: if it is jpeg image then,

extension = image/jpeg

or if pdf then,

extension = application/pdf

To obtain the exact value, perform extension.replace(/(.*)\//g, ''). you will get the value.

Dhatri Suresh
  • 811
  • 7
  • 5
  • 13
    This is very neat, but comes with a "but"... The `type` property might return empty strings. For example, if you upload a docx file as a client, but don't have MS Word installed on your client machine, then the browser returns an empty string on `type`. Fallback mechanisms are necessary. This behaves differently though in each browser. I've seen this empty string result on `type` with the latest/recent Chrome version and no MS Word installed on my dev machine. – Michael Jul 09 '20 at 12:24
  • 1
    That regex pattern will only remove the `/`. Should be `extension.replace(/(.*)\//g, '')` – Crayons Mar 28 '21 at 14:12
  • @Crayons Yes...Thank you – Dhatri Suresh Mar 30 '21 at 12:50
  • Incase I upload the *.docx file it returns like this. `application/vnd.openxmlformats-officedocument.wordprocessingml.document` How can I get only extension "docx"? – SatelBill Apr 05 '22 at 08:43
51

Use lastIndexOf to get the last \ as an index and use substr to get the remaining string starting from the last index of \

function getFile(filePath) {
        return filePath.substr(filePath.lastIndexOf('\\') + 1).split('.')[0];
    }

    function getoutput() {
        outputfile.value = getFile(inputfile.value);
        extension.value = inputfile.value.split('.')[1];
    }
<input id='inputfile' type='file' name='inputfile' onChange='getoutput()'><br>
    Output Filename <input id='outputfile' type='text' name='outputfile'><br>
    Extension <input id='extension' type='text' name='extension'>

UPDATE

function getFileNameWithExt(event) {

  if (!event || !event.target || !event.target.files || event.target.files.length === 0) {
    return;
  }

  const name = event.target.files[0].name;
  const lastDot = name.lastIndexOf('.');

  const fileName = name.substring(0, lastDot);
  const ext = name.substring(lastDot + 1);

  outputfile.value = fileName;
  extension.value = ext;
  
}
<input id='inputfile' type='file' name='inputfile' onChange='getFileNameWithExt(event)'><br>
  Output Filename <input id='outputfile' type='text' name='outputfile'><br>
  Extension <input id='extension' type='text' name='extension'>
Junius L
  • 15,881
  • 6
  • 52
  • 96
13
var filePath = $("#inputFile").val(); 
var file_ext = filePath.substr(filePath.lastIndexOf('.')+1,filePath.length);
console.log("File Extension ->-> "+file_ext);

It will work if you have dots in filename.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Poorna
  • 191
  • 1
  • 5
3

First get the filename, then slice it to various parts.

const media_file = event.target.files[0] // event is from the <input> event
const filename = media_file.name

let last_dot = filename.lastIndexOf('.')
let ext = filename.slice(last_dot + 1)
let name = filename.slice(0, last_dot)
chidimo
  • 2,684
  • 3
  • 32
  • 47
2

You could try this out:

var fullPath = inputfile.value.split('.')[0];
var filename = fullPath.replace(/^.*[\\\/]/, '');
outputfile.value=filename;`

This should remove everything except the filename.

I got it from How to get the file name from a full path using JavaScript?.

Community
  • 1
  • 1
Valentin Gavran
  • 341
  • 9
  • 21
2

Here is a handy code.

    String extension = fileName.substring(fileName.lastIndexOf('.')+1);
    String name = fileName.substring(0, fileName.lastIndexOf('.'));
Remario
  • 3,813
  • 2
  • 18
  • 25
1

Simple and quick.

   var files = event.target.files[0]
   // for getting only extension 
   var fileExtension = files.type.split("/").pop();
   var fileName = files.name
Salman Mehmood
  • 263
  • 2
  • 6
0

from file[0].type you can get the extension

file[0] looks like File { name: "hcl_icon.ico", lastModified: 1559301004000, webkitRelativePath: "", size: 1150, type: "image/x-icon" }

or by File reader reader.onload = function (e){} e.target.result gives the src of the file contains Data have extension

0

With less code

let fileName = "profile.png";
let extension = fileName.split(".").pop();
burak isik
  • 395
  • 5
  • 6
0

I use this to get the filename and the extension

For file name:

this.files[0].name.slice(0, this.files[0].name.lastIndexOf("."))

For file extension:

this.files[0].name.slice(this.files[0].name.lastIndexOf(".") + 1, this.files[0].name.length)

Sample code:

document.getElementById("file").oninput = function() {
    console.log("File name: "+this.files[0].name.slice(0, this.files[0].name.lastIndexOf(".")))
    console.log("File extension: "+this.files[0].name.slice(this.files[0].name.lastIndexOf(".") + 1, this.files[0].name.length))
}

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <input type="file" id="file">
</body>
<script>
document.getElementById("file").oninput = function(val) {
    console.log("File name: "+this.files[0].name.slice(0, this.files[0].name.lastIndexOf(".")))
    console.log("File extension: "+this.files[0].name.slice(this.files[0].name.lastIndexOf(".") + 1, this.files[0].name.length))
}
</script>

Hope this helps