选择文件后自动获得输入中的文件名

时间:2019-03-03 12:41:22

标签: javascript php html

我正在做我的上传文件页面,并且我的页面上有一个<input>,用户可以在其中为他的文件写一个名字,还有一个<input>,用户可以在其中选择一个文件。 / p>

我想要做的是,在用户选择文件之后,输入的名称将自动填充为文件名(不带扩展名)。

我的html代码看起来像这样

<div class="card-header text-center" data-background-color="rose" style="margin-left: 15px;">
     <h3 class="card-title">Upload file</h3>
</div>
<div class="card-content">
     <div class="input-group">
         <span class="input-group-addon"></span>
    
      <div class="form-group label-floating">
           <label class="control-label"><h4>Chose a name</h4></label><br>
           <input type="text" name="name" id="name" class="form-control" value="" required>
     </div>
    
     <div class="form-group label-floating">
           <label class="control-label"><h4>Choose a file</h4></label><br>
           <input type="file" id="file" name="file" required>
     </div>
</div>
</div>

我希望在选择文件后立即填充它,因为我在面向对象的编程中这样做,因此无法重新加载页面,因为我拥有csrf。  我要在获得名称之后,用上载文件的名称填充。

2 个答案:

答案 0 :(得分:4)

添加此代码即可完成您想要的操作,在JQuery中会更容易,但是当您指定javascript时,我将其全部保留为纯JS。

<script>
    file.onchange = function(e) { 
        //Get the file path
        var fileName = document.getElementById("file").value; 
        //Get the filename
        var fileName2 = fileName.replace(/^.*[\\\/]/, '');
        //Remove the extension and set the input text
        document.getElementById("name").value = fileName2.replace(/\.[^/.]+$/, ""); 
    };
</script>

答案 1 :(得分:0)

我已经更新了您的代码,如果需要澄清,请告诉我

open import Common.IO
open import Common.String

f  : String  → String
f  x  =  x + ' second string'

main = putStrLn (f  "Hello, world!")

相关问题