显示所选文件的名称

时间:2018-06-02 13:32:35

标签: javascript php file

我想在用户选择要上传的文件后显示文件名。这里是我需要此功能的网站:MB@ Consulting - Upload File Page

我已经定制了css和php文件,如下所示:

<div class="inputfile-box">
    <label for="file">

        <input type="file" id="file" class="inputfile" name="file"  onchange="fileSelected(this);" />

        <span id="file-name" class="file-box"></span>

        <span class="file-button"><i class="fa fa-folder-open"></i>
          Scegli file
        </span>

    </label>

    <label class="custom-file-start-upload">
        <input type="submit" name="submit" onclick="startUploading()" />
        <i class="fa fa-play"></i> Upload
    </label>
</div>

CSS是:

// Hide input old style
input[type="file"] {
    display: none;
}

input[type="submit"] {
    display: none;
}

// Style of label
.custom-file-start-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}    

.file-box, .file-button {
    cursor: pointer;
}

.file-box-send, .file-button-send {
    cursor: pointer;
}

 .custom-file-start-upload {
    background-color: #62ea62;
}

.inputfile-box {
  position: relative;
    width:100%;
    max-width: 360px;
}

.inputfile {
  display: none;
}

.container {
  display: inline-block;
  width: 100%;
}

.file-box {
  display: inline-block;
  width: 100%;
  border: 1px solid;
  padding: 5px 0px 5px 5px;
  box-sizing: border-box;
  height: calc(2rem - 2px);
    min-height: 36px;
}

.file-button {
  background: #d52727;
  padding: 5px;
  position: absolute;
  border: 1px solid #000000;
  top: 0px;
  right: 0px;
  color: #FFFFFF;
}

我从另一个页面(Example)获取了此函数的代码 在演示页面工作,但不在我的网站上工作! 我尝试添加这个JS:

<script type="text/javascript">
    function fileSelected(target) {
        document.getElementById("file-name").innerHTML = target.files[0].name;
    }
</script>

但文件名不会显示在单独的字段“file-name”中。

2 个答案:

答案 0 :(得分:1)

您的JavaScript代码正在运行,但您网站中某些插件的JavaScript令人惊讶地具有与您在HTML中的onchange事件中使用的名称相同的功能。您需要将函数名称更改为唯一的名称。

<input type="file" id="file" class="inputfile" name="file" onchange="fileIsSelected(this);">

我已在此处将功能名称更改为fileIsSelected。您还需要在JavaScript中更改名称。

<script type="text/javascript">
    function fileIsSelected(target) 
    {
        document.getElementById("file-name").innerHTML = target.files[0].name;
    }
</script>

答案 1 :(得分:0)

为了解决我的问题,我在intput字段中添加了第二个函数,因此它同时运行旧的和新的函数(onchange =“fileSelected()  和fileIsSelected(this))。

这:

<input type="file" id="file" class="inputfile" name="file"  onchange="fileSelected(); fileIsSelected(this);" />

并使用JS:

<script type="text/javascript">
    function fileIsSelected(target) 
    {
        document.getElementById("file-name").innerHTML = target.files[0].name;
    }
</script>

谢谢:)