CheeseFlavored
CheeseFlavored

Reputation: 2112

javascript - get the filename and extension from input type=file

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'>

Upvotes: 56

Views: 171688

Answers (11)

Sanka Sanjeeva
Sanka Sanjeeva

Reputation: 3520

Apart from the below answers, we can use Array.prototype.at() to get a file extension after splitting by dots

const name = "name.with.dots.png";

const extension = name.split('.').at(-1);

console.log(extension); // png

Upvotes: 1

Chencho Namgyel
Chencho Namgyel

Reputation: 1

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

Upvotes: 0

burak isik
burak isik

Reputation: 571

With less code

let fileName = "profile.png";
let extension = fileName.split(".").pop();

Upvotes: 4

Dhatri Suresh
Dhatri Suresh

Reputation: 859

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.

Upvotes: 67

Junius L
Junius L

Reputation: 16132

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'>

Upvotes: 56

Remario
Remario

Reputation: 3863

Here is a handy code.

    String extension = fileName.substring(fileName.lastIndexOf('.')+1);
    String name = fileName.substring(0, fileName.lastIndexOf('.'));

Upvotes: 2

Salman Mehmood
Salman Mehmood

Reputation: 283

Simple and quick.

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

Upvotes: 2

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

Upvotes: 0

chidimo
chidimo

Reputation: 2948

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)

Upvotes: 4

Poorna
Poorna

Reputation: 199

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.

Upvotes: 14

Valentin Gavran
Valentin Gavran

Reputation: 373

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?.

Upvotes: 2

Related Questions