javascript-从输入type = file获取文件名和扩展名 [英] javascript - get the filename and extension from input type=file

查看:82
本文介绍了javascript-从输入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).

该扩展名可以正常使用,但文件名还显示了路径,该路径为我提供了falsepath警告.

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

推荐答案

使用 lastIndexOf 以获得最后一个 \ 作为索引,并使用 substr 来从 \

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

更新

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

这篇关于javascript-从输入type = file获取文件名和扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆