2016-04-21 86 views
3

我有一个表格上传图片提供:获取图像的文件名 - 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> 

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

+0

请向我们展示标记/ HTML。 – rmondesilva

回答

4

可以使用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] : ''); 
 

 
})
<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" />

+1

如果我上传名为'employees_db-full-1.0.6.tar.bz2'的文件,则打印的值显示为'employees_db-full-1',在扩展名前截断一些实际文件名 – ThisClark

+0

您节省了大部分时间,谢谢。 – DinhNgocHien

0

可以使用有选择的文件的名称,大小和类型的详细信息下面的代码。看一看。

<form enctype="multipart/form-data"> 
<input id="file" type="file" /> 
<input type="submit" value="Upload" /> 
</form> 
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 
<script> 
$('#file').change(function(){ 
var file = this.files[0]; 
name = file.name; 
size = file.size; 
type = file.type; 
//your validation 
}); 
</script> 
1

您可以将用户之后的事件选择这样的图像:

$(document).ready(function() { 
    $('#image').on('change', function(event) { 
     // and you can get the name of the image like this: 
     console.log(event.target.files[0].name); 
    }); 
}); 

如果HTML是这样的:

<input type="file" id="image"> 
0

使用此示例代码来显示文件名:

<input type="file" name="file" id="file" /> 
<button id="btn">Submit</button> 
<div id="fname"></div> 

$(function(){ 
    $('#btn').on('click',function(){ 
    var name = $('#file').val().split('\\').pop(); 
    name=name.split('.')[0]; 
    $('#fname').html(name); 
    }); 
})(); 

这里是Demo jsfiddle

+1

好的答案,它的工作。 –

+0

感谢兄弟...乐于帮助 –