开发者

How to get a extension of a file using jquery or javascript? [duplicate]

This question already has answers here: How can I get file extensions with JavaScript? 开发者_Python百科 (36 answers) Closed 8 years ago.

i want to check the type of uploaded file. If name like example.txt, i want to get the .txt part only. How can i achieve it using Jquery or javascript.

Any Suggestions or links would be appreciative!!!


A simple solution is .split() and .pop() to get the last string in the array, like this:

var ext = fileName.split('.').pop();

This will get you just "txt" without the ., just append if needed. This also works on say: My.File.name.has.an extension.txt as well. If it doesn't have an extension it'll return the file name, so you may want to check for this...or go a completely different direction and validate against a set or known extensions via regex.


Use lastIndexOf() and substr():

function getFileExtension(name)
{
    int found = name.lastIndexOf('.') + 1;
    return (found > 0 ? name.substr(found) : "");
}

Note that this implementation returns an empty string if the filename doesn't contain any period character (i.e. has no extension). Implementations based on split() sometimes return the full filename in that case.


If you need to validate multiple extensions:

var filename = "picture.jpg";
var valid_extensions = /(\.jpg|\.jpeg|\.gif)$/i;   
if(valid_extensions.test(filename))
{ 
   alert('OK');
}
else
{
   alert('Invalid File');
}

This eliminates the need to parse the string if you want to check the extension, for example, before uploading a file.


var text = 'example.txt',
    ext  = text.split('.')[1];


    if((document.form1.upload.value.lastIndexOf(".jpg")==-1) {
   alert("Please upload only .jpg extention file");
   return false;
}

lastIndexOf will return the index of the last occurrence of the specified search argument. If not found, -1 will return


Split the entire file name with . as the delimitter.The split will store the splitted items in an array.Take the last element of the array.


Frédéric's answer worked well for me, however, the function keep erroring out in Chrome console with "Unexpected identifier". The "int" was issue and this modification worked.

function getFileExtension(name){
  var found = name.lastIndexOf('.') + 1;
  return (parseInt(found) > 0 ? name.substr(found) : "");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜