当提交按钮和浏览按钮被单个按钮替换时,无法上传文件

I tried to combine the browse button and submit button together .When the button is clicked , Iam able to select the file.

But the file doesn't get uploaded

This is the form

HTML:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>" method="post" id="myform" enctype="multipart/form-data">
    <input type="file" name="upload" id="upload" style="display:none">
    <button id="browse">Upload</button>
</form>

JQuery

$(document).ready(function(){
        $("#upload").change(function(){
                $("#myform").submit();
        });
        $("#browse").click(function(){
        $("#upload").click();
        });

    });

Then I submitted the data

PHP :

if($_SERVER["REQUEST_METHOD"]=="POST")
{

    $file=$_FILES["upload"]["name"];
    $folder='uploads/';
    $err=$_FILES["upload"]["error"];
    $target=$folder.$file;
    $temp=$_FILES["upload"]["tmp_name"];
    echo $err;
    move_uploaded_file($temp, $target);
}

I got the output as 4 . This means that no file was uploaded .How can i resolve this issue?

There is a easy an elegant way to achieve that.

  • Add the type="submit" to the button because not all web browser are using "submit" as default button type
  • Add a form event listener that triggers when "submit" event is raised

Example code:

$(document).ready(function(){
  
  $('#myform').submit(function(e) {
    
    // Remove following two lines in order to perform the submission
    // I added the two lines in order to avoid the real submission (Test purposes)
    e.preventDefault(); 
    alert('Submitted!')
    
  })
  
  $("#upload").change(function(){
    $("#myform").submit();
  }); 

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="example.html" method="post" id="myform" enctype="multipart/form-data">
    <input type="file" name="upload" id="upload">
    <button id="browse">Upload</button>
</form>

Remember to remove the "preventDefault" and the "alert" lines that I included in order to execute the code snippet without redirect you to another page.

</div>