如何在输入类型文件中显示选择了哪个文件?

时间:2015-04-02 10:20:35

标签: javascript jquery html css input-type-file

使用下面的代码,我编辑了我的INPUT TYPE FILE按钮的样式。我现在遇到的问题是它没有显示用户选择了哪个文件。我不知道该怎么做.. :(

HTML代码:

<div class="giz-upload">
<input type="file" size="40" name="d4p_attachment[]">
</div>

的style.css

div.giz-upload{
    width: 157px;
    height: 57px;
    background: url(http://www.gizmoids.com/wp-content/sicons/upload.png);
background-size: 80px 60px;
background-repeat:no-repeat;
overflow: hidden;
}

div.giz-upload input {
    display: block !important;
    width: 157px !important;
    height: 57px !important;
    opacity: 0 !important;
    overflow: hidden !important;
}

这是JSFIDDLE网址:http://jsfiddle.net/sunita1993/avn9n6sp/

3 个答案:

答案 0 :(得分:1)

请检查以下代码,希望它能正常工作:)

$('input[type=file]').change(function (e) {
    $(this).parents('.giz-upload').find('.element-to-paste-filename').text(e.target.files[0].name);
});
.giz-upload {
    display: block !important;
    height: 57px !important;
    background: url(http://www.gizmoids.com/wp-content/sicons/upload.png);
    background-size: 80px 60px;
    background-repeat:no-repeat;
    padding-left: 90px; 
}
.giz-upload input {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<label class="giz-upload">
    <input type="file" size="40" name="d4p_attachment[]" />
    <span class="element-to-paste-filename"></span>
</label>

答案 1 :(得分:0)

你可以使用javascript来做到这一点。我举一个使用jQuery框架的例子:

$(function() {

    $("input").on("change", function() {

        var file = this.files;
        console.log(file);

    });

});

当您选择一个文件时,输入值将会改变,您可以访问该文件,file变量将包含一个包含该文件数据的对象,您可以从中获取所需内容并将其放入span元素或您想要的地方

JsFiddle

上的示例

答案 2 :(得分:0)

因为在div.giz-upload input中,您将opacity属性设置为0。

删除不透明度,它将显示文件名。