首页 > 解决方案 > 如何将上传文件的名称设置为输入类型:html中javascript上的文本

问题描述

我想向我的 html 页面添加一个文件上传控件,如下所示。

<input class="form-control valid" id="rptScreenShot" type="text" style="float:left;" runat="server"
                               data-val="true" data-val-maxlength="The field Report Sample must be a string or array type with a maximum length of '600'." 
                               data-val-maxlength-max="600" value="" aria-invalid="false" />
<label class="btn btn-default btn-file">
    Browse <input class="form-control" id="upld_sample1" type="file" name="file_rptsample1" style="display: none;">
</label>

我无法做到的是在用户浏览文件后捕获选定的文件,并通过 javascript 或 jquery 将其设置为 rptScreenShot 的值。任何帮助,将不胜感激。

标签: javascriptjqueryhtmlfile-uploadhtml-input

解决方案


像下面这样的东西?

$("#upld_sample1").on("change", function(e){
  console.log("Fileinfo:", e.target.files[0])
  $("#rptScreenShot").val(e.target.files[0].name)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control valid" id="rptScreenShot" type="text" style="float:left;" runat="server" data-val="true" data-val-maxlength="The field Report Sample must be a string or array type with a maximum length of '600'." data-val-maxlength-max="600"
  value="" aria-invalid="false" />
<label class="btn btn-default btn-file">
    Browse <input class="form-control" id="upld_sample1" type="file" name="file_rptsample1" style="display: none;">
</label>


推荐阅读