简体   繁体   English

从文件 url 获取扩展名

[英]Get extension from a file url

I am using file(input) to select a file.我正在使用 file(input) 来选择一个文件。 I want to retrieve the file extension(.jpeg) from a URL C:\Users\Rajat\Pictures\pic1.jpeg .我想从 URL C:\Users\Rajat\Pictures\pic1.jpeg检索文件扩展名(.jpeg)。 Then after that I want to put the URL into a text box according to their format ie audio, video and image.然后,我想根据它们的格式(即音频、视频和图像)将 URL 放入文本框中。

Try this:尝试这个:

var url='C:\Users\Rajat\Pictures\pic1.jpeg';
var parts=url.split('.');
console.log(parts[parts.length-1]);

In that case you better go with mimetype instead of extensions.在这种情况下,您最好使用 mimetype 而不是扩展。

var fileInput = document.getElementById('your-file-input-id');
var fileType = fileInput.files[0].type;
console.log(fileType);//gives image/jpeg or audio/mp3
var parts = filetype.split('/');
parts[0];//image
parts[1];//jpeg

Using ES2022's Array.at() method (see link for browser support), you can do it in a one liner like so:使用 ES2022 的Array.at()方法(请参阅浏览器支持的链接),您可以像这样在单行中执行此操作:

 const url = "https://example.com/my-file.jpg"; const extension = url.split(".")?.at(-1); console.log(extension);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM