【问题标题】:Form action field unable to upload and move to new page together表单操作字段无法一起上传和移动到新页面
【发布时间】:2014-06-20 14:40:51
【问题描述】:

已编辑:@James 回答的解决方案在下面的代码中以粗体显示。 再次感谢@James。


我有一个表单(HTML),它有一个文本字段并将文件上传到数据库。 在我使用之前

    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" name="form1" enctype="multipart/form-data"></pre>

工作正常,现在我希望页面将条目提交到数据库并显示不同的页面,所以我尝试了这个

    <form action="page3.php"......>, but didn't worked.

但是,当我单击提交按钮时,它会在数据库中输入文本字段,但不会将文件上传到数据库。 我想要它做的是:当我单击提交按钮时,在数据库中输入文本字段,文件被上传到数据库文件夹(并且我的程序将其路径输入到数据库),并加载新页面供用户查看.

感谢任何帮助。谢谢。 我的php代码

    <?php

    //ob_start();
    $host="localhost";
    $username="root";
    $password="";
    $db_name="newrep";
    $table_name="members";

    $conn=new mysqli('localhost','root','','newrep');
    if(!$conn){
        die("cannot connect.");
    }
    //else if(!mysql_select_db($db_name)){
      //  die(" cannot select database.");
    //}

    session_start();
    use foundationphp\UploadFile;
    echo "Session value: ".$_SESSION['texas'];
    $currentuser=$_SESSION['texas'];
     echo $currentuser;
     $current_year=date("Y");

     //code for upload starts here
    require_once 'src/foundationphp/UploadFile.php';
    if (!isset($_SESSION['maxfiles'])) {
    $_SESSION['maxfiles'] = ini_get('max_file_uploads');
    $_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
    $_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']);
    }
    $max = 2048 * 1024;
    $result = array();
    //upload code ended above
    if(!isset($_SESSION['texas'])) 
    {
      header('Location:login_page.php');
      exit();
   }
   else {
    if(isset($_POST['title'])){
      echo "reaching the else";
      if(isset($_POST['upload'])){
      //upload in POST is for upload
        print_r($_FILES);
      $destination = __DIR__ . '/uploaded/'; //for upload
      //upload code try and catch
      try {
      $upload = new UploadFile($destination);
      $upload->setMaxSize($max);
      //$upload->allowAllTypes();
      $upload->upload();
      $result = $upload->getMessages();
        } 
      catch (Exception $e) {
        $result[] = $e->getMessage();
        }
      } 
    $error = error_get_last();
    if ($result || $error){ 
    //<ul class="result">
    if ($error){
    echo "{$error['message']}"; }
    if ($result) {
    foreach ($result as $message) {
    echo "<li>$message</li>";}}}

    $file_path_variable= $destination.$_SESSION['current_filename'];
    echo $file_path_variable;

    $title=$_POST['title'];

    $query="INSERT INTO proposal(title_prop, userName_prop,whitepaper_prop,year_prop) VALUES('$title','$currentuser','$file_path_variable','$current_year')";

    $result_query=mysqli_query($conn,$query);

   echo "      in elseif         ";
    if(!$result_query){
      echo " cannot insert ";
    }
    else {
**header('Location: page3.php');
exit();**
      //echo "successful entry ";
    }
   }
    //ob_end_flush();    
 ?>

此处为 HTML 代码:

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Online Application</title>
  <!--  <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> -->
  <link href="bootstrap.min.css" rel="stylesheet">
<head><script src="bootstrap.min.js"></script> </head>
<body>
    <div id="O_o"><br><h4>Texas State University</h4></div>
<div id="wrapper">
      <form action=**"<?php $_SERVER['PHP_SELF']?>"** method="POST" id="whitepaper" name="whitepaper" role="form" enctype="multipart/form-data">
<legend><h5><b>Online Application</b></h5></legend>

          <h4 id="reference" name="reference" class="heading-reference"><b>Proposal Whitepaper</b></h4>

<fieldset>
<center>
<div class="form-group">
 <?php echo "Year of Proposal: $current_year";?><br> 
<label class="label_title control-label" for="title">Submit Title of your proposal:</label>
<input id="title" name="title" type="text" placeholder="" class="input_title form-control" >
<p class="help-block">All fields are required.</p><!--
<button type="submit" id="submit_button" name="btn-primary" class="btn btn-primary"> Submit Title </button>-->
</div>



<div class="form-group">
<label class="label_whitepaper control-label" for="file">Upload the whitepaper of your proposal here: <br>Only .docx , .doc and .pdf format extensions are permitted.</label>

<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max;?>">

<p><input type="file" id="filename" name="filename[]" title="Browse for whitepaper" class="btn-primary" multiple
  data-maxfiles="<?php echo $_SESSION['maxfiles'];?>"
  data-postmax="<?php echo $_SESSION['postmax'];?>"
  data-displaymax="<?php echo $_SESSION['displaymax'];?>"></p>

File should be no more than <?php echo UploadFile::convertFromBytes($max);?>.<br>
<!--<p><input type="submit" name="upload" value="Upload File" class="btn-primary">-->
<button id="submit" name="upload" class="btn-primary" >Submit and continue</button>
</div>

</center>


</fieldset>
</form>
</div>
<script src="js/checkmultiple.js"></script>
<script src="jquery.min.js"></script>
<script src="prettify.js"></script>
<script src="bootstrap.file-input.js"></script>
<script>
$(document).ready(function(){
  $('input[type=file]').bootstrapFileInput();
});
</script>
</body>
</html>
<?php } 
mysqli_close($conn);
?>

【问题讨论】:

  • 你的代码都没有通过。
  • 只是猜测,你在第 37 行有错误
  • 刚刚编辑了帖子,请查看。谢谢
  • 有人可以帮忙吗.. 有什么建议吗?
  • 另外,如果你把整个表单放在这里,从开始的表单标签到结束的表单标签,会更容易发现问题。

标签: php mysql html forms mysqli


【解决方案1】:

您需要在表单标签中包含enctype='multipart/form-data'

<form action='<?php echo $_SERVER['PHP_SELF']?>' method="POST" name="form1" enctype='multipart/form-data'>

没有它,附件将无法通过表单发送。

更新

试试下面的代码。我还修复了一些 HTML 错误。

<?php

    //ob_start();
    $host="localhost";
    $username="root";
    $password="";
    $db_name="newrep";
    $table_name="members";

    $conn=new mysqli('localhost','root','','newrep');
    if(!$conn){
        die("cannot connect.");
    }
    //else if(!mysql_select_db($db_name)){
      //  die(" cannot select database.");
    //}

    session_start();
    use foundationphp\UploadFile;
    echo "Session value: ".$_SESSION['texas'];
    $currentuser=$_SESSION['texas'];
    echo $currentuser;
    $current_year=date("Y");

    //code for upload starts here
    require_once 'src/foundationphp/UploadFile.php';
    if (!isset($_SESSION['maxfiles'])) {
        $_SESSION['maxfiles'] = ini_get('max_file_uploads');
        $_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
        $_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']);
    }

    $max = 2048 * 1024;
    $result = array();
    //upload code ended above
    if(!isset($_SESSION['texas'])) 
    {
        header('Location:login_page.php');
        exit();
    }else {
        if(isset($_POST['title'])){
            echo "reaching the else";
            if(isset($_POST['upload'])){
                //upload in POST is for upload
                print_r($_FILES['fieldname']);
                $destination = __DIR__ . '/uploaded/'; //for upload
                //upload code try and catch
                try {
                    $upload = new UploadFile($destination);
                    $upload->setMaxSize($max);
                    //$upload->allowAllTypes();
                    $upload->upload();
                    $result = $upload->getMessages();
                }catch (Exception $e) {
                    $result[] = $e->getMessage();
                }
            } 
            $error = error_get_last();
            if ($result || $error){ 
                //<ul class="result">
                if ($error){
                    echo "{$error['message']}"; }
                if ($result) {
                    foreach ($result as $message) {
                    echo "<li>$message</li>";
                    }
                }
            }

            $file_path_variable= $destination.$_SESSION['current_filename'];
            //echo $file_path_variable;

            $title=$_POST['title'];

            $query="INSERT INTO proposal(title_prop, userName_prop,whitepaper_prop,year_prop) VALUES('$title','$currentuser','$file_path_variable','$current_year')";

            $result_query=mysqli_query($conn,$query);

            //echo "      in elseif         ";
            if(!$result_query){
                echo " cannot insert ";
            }else {
                header('Location: page3.php');
                exit();
                //echo "successful entry ";
            }
        }
        //ob_end_flush();    
        ?>

        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">

                <title>Online Application</title>
                <!--  <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> -->
                <link href="bootstrap.min.css" rel="stylesheet">
                <script src="bootstrap.min.js"></script>
            </head>
            <body>
                <div id="O_o"><br><h4>Texas State University</h4></div>
                <div id="wrapper">
                    <form action="<?php= $_SERVER['PHP_SELF']?>" method="POST" id="whitepaper" name="whitepaper" role="form" enctype="multipart/form-data">
                        <fieldset>
                            <legend><h5><b>Online Application</b></h5></legend>

                            <h4 id="reference" name="reference" class="heading-reference"><b>Proposal Whitepaper</b></h4>
                            <center>
                                <div class="form-group">
                                    <?php echo "Year of Proposal: $current_year";?><br> 
                                   <label class="label_title control-label" for="title">Submit Title of your proposal:</label>
                                   <input id="title" name="title" type="text" placeholder="" class="input_title form-control" >
                                   <p class="help-block">All fields are required.</p><!--
                                   <button type="submit" id="submit_button" name="btn-primary" class="btn btn-primary"> Submit Title </button>-->
                                </div>

                                <div class="form-group">
                                    <label class="label_whitepaper control-label" for="file">Upload the whitepaper of your proposal here: <br>Only .docx , .doc and .pdf format extensions are permitted.</label>

                                    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max;?>">

                                    <p><input type="file" id="filename" name="filename[]" title="Browse for whitepaper" class="btn-primary" multiple
                                      data-maxfiles="<?php echo $_SESSION['maxfiles'];?>"
                                      data-postmax="<?php echo $_SESSION['postmax'];?>"
                                      data-displaymax="<?php echo $_SESSION['displaymax'];?>"></p>

                                    File should be no more than <?php echo UploadFile::convertFromBytes($max);?>.<br>
                                    <!--<p><input type="submit" name="upload" value="Upload File" class="btn-primary">-->
                                    <button id="submit" name="upload" class="btn-primary" >Submit and continue</button>
                                </div>
                            </center>
                        </fieldset>
                    </form>
                </div>

                <script src="js/checkmultiple.js"></script>
                <script src="jquery.min.js"></script>
                <script src="prettify.js"></script>
                <script src="bootstrap.file-input.js"></script>
                <script>
                    $(document).ready(function(){
                        $('input[type=file]').bootstrapFileInput();
                    });
                </script>
            </body>
        </html>
    <? } 
    mysqli_close($conn);
?>

【讨论】:

  • 我在我的真实代码中有这个,我只是在这里省略了它,以为很明显......对不起。我的问题是当我提交它时不会上传文件并将控件移动到用户的新页面。
  • 那么如果你在处理上传的页面上打印出print_r($_FILES['fieldname']);,你会得到什么?
  • 我在具有表单标签的同一页面上进行了尝试,因为它具有大部分上传和数据库条目代码。什么都没发生。似乎上传甚至没有启动,因为我的上传代码中都有回显以进行错误检查
  • 我不确定你的意思。我以为您指向的页面不是表单所在的页面?还是您的意思是您现在将其指向同一页面?另外,你能发布你的整个表单代码和你的PHP处理代码吗?
  • @AryaSingh 我看到你也把fieldname 放在你的print_r 中。您需要将其替换为表单的文件字段名称。但是,您可以只做print_r($_FILES);,我应该从一开始就说。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
  • 2017-03-22
  • 2022-10-04
  • 2011-07-06
  • 2019-01-17
  • 1970-01-01
  • 2018-05-04
相关资源
最近更新 更多