代码之家  ›  专栏  ›  技术社区  ›  Parth Shah

表单的上载文件在取消新文件选择时消失

  •  1
  • Parth Shah  · 技术社区  · 8 年前

    我的网页上有一个简单的表单。

        <form action="upload.php" method="post" enctype="multipart/form-data">
            Select image to upload:
            <input id="browse" type="file" name="fileToUpload" id="fileToUpload">
            <input type="submit" value="Upload Image" name="submit">
        </form>

    现在,我的问题是,当我浏览并选择要上载的文件时,它会显示我要上载的文件。 enter image description here 但当我点击“选择文件”并再次浏览时,这次如果中途改变主意并点击“取消”,则旧的选定图像也会消失。 enter image description here

    取消时,它还会删除已选择的图像。

    enter image description here

    为什么会发生这种情况?如果我想在再次浏览并取消后选择旧的选定图像,该怎么办?

    提前感谢!

    1 回复  |  直到 8 年前
        1
  •  2
  •   Parth Shah    8 年前

    感谢@Carlos,添加了此javascript

    var input = document.getElementById("browse");
    var selectedFile;
    input.addEventListener('change', updateImageDisplay);
    function updateImageDisplay() {
        if(input.files.length==0) {
            input.files = selectedFile;
       }
       else {
           selectedFile = input.files;
       }
    }
    

    现在它工作得很好!您可以检查 here .