在上传之前获取图像的文件名--JQuery

Din*_*ien 3 javascript jquery

我有一个表单上传图像:

<div class="col-sm-4">
 <input id="file_input" type="file" style="visibility: hidden; width: 0; height: 0" name="image[photo_new]" accept="image/*">
</div>
<div class="col-lg-8">
  <div class="form-group row">
    <label class="col-sm-3 control-label" for="title">
      <label for="image_title">Title</label>
    </label>
    <div class="col-sm-9">
      <input id="title" class="form-control" type="text" placeholder="Title" name="image[title]" maxlength="200">
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我想当用户点击#input_file区域选择图像,然后选择文件后,文件名将立即显示在#title字段中.例如name.png应该name.我想用JQuery来做这个功能,但不知道如何,任何建议?预先感谢.

Aru*_*hny 7

您可以使用this.value在更改事件处理程序中获取文件值,然后提取名称

$('#file_input').change(function() {
  //$('#title').val(this.value ? this.value.match(/([\w-_]+)(?=\.)/)[0] : '');
  $('#title').val(this.files && this.files.length ? this.files[0].name.split('.')[0] : '');

})
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="file_input" type="file" />
<input id="title" />
Run Code Online (Sandbox Code Playgroud)