javascript - 从 input type=file 获取文件名和扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43708127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:07:02  来源:igfitidea点击:

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

javascripthtmlformsfile-uploadinput

提问by CheeseFlavored

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

回答by Dhatri Suresh

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,

在类型中,您会找到扩展名,例如:如果它是 jpeg 图像,则

extension = image/jpeg

or if pdf then,

或者如果pdf然后,

extension = application/pdf

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

要获得确切的值,请执行 extension.replace(///g, '')。你会得到价值。

回答by Junius L.

Use lastIndexOfto get the last \as an index and use substrto get the remaining string starting from the last index of \

使用lastIndexOf获取最后一个\作为索引,使用substr获取从最后一个索引开始的剩余字符串\

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

回答by Poorna

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.

如果文件名中有点,它将起作用。

回答by Valentin Gavran

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

我从如何使用 JavaScript 从完整路径获取文件名?.

回答by chidimo

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)

回答by Rashmi HazeL ivy DorisFay

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

从 file[0].type 你可以得到扩展名

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

file[0] 看起来像 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

或通过 File reader reader.onload = function (e){} e.target.result 给出文件的 src contains Data 有扩展名

回答by Salman Mehmood

Simple and quick.

简单快捷。

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

回答by Remario

Here is a handy code.

这是一个方便的代码。

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