首页 > 解决方案 > 我有一个可以提交的表单,但是当我添加文件上传功能时它不起作用

问题描述

我正在尝试创建一个表单,我可以在其中向数据库提交一些信息以及上传文件。如果我仅使用带有method=post的表单,则该表单效果很好,但是,经过一些研究,我发现我需要使用带有 action 的表单,这是一个附加的链接。所以我创建了一个可以很好地上传文件的upload.php文件。但是,现在表单不提交,但上传功能有效。我想像以前一样提交表单,但是当附加文件时,我希望它也上传它,当没有选择文件时,站点必须只提交表单。谢谢

<?php include_once('config.php');
include_once('header.php');
if(isset($_REQUEST['submit']) and $_REQUEST['submit']!=""){
    extract($_REQUEST);
    if($description==""){
        header('location:'.$_SERVER['PHP_SELF'].'?msg=un');
        exit;
    }elseif($cost==""){
        header('location:'.$_SERVER['PHP_SELF'].'?msg=ue');
        exit;
    }elseif($type==""){
        header('location:'.$_SERVER['PHP_SELF'].'?msg=up');
        exit;
    }elseif($location==""){
        header('location:'.$_SERVER['PHP_SELF'].'?msg=u2');
        exit;   
    }else{
        
        //$userCount    =   $db->getQueryCount('customers','id');
            $data   =   array(
                            'description'=>$description,
                            'cost'=>$cost,
                            'type'=>$type,
                            'location'=>$location,
                            'month'=>$month,
                            'year'=>$year,
                            'day'=>$day,
                            'datee'=>$datee,        
                        );
            $insert =   $db->insert('costs',$data);
            if($insert){
                header('location:properties.php?msg=ras');
                exit;
            }else{
                header('location:properties.php?msg=rna');
                exit;
            }
            exit;
        }
   }
?
<!doctype html>
<html lang="en-US" xmlns:fb="https://www.facebook.com/2008/fbml" xmlns:addthis="https://www.addthis.com/help/api-spec"  prefix="og: http://ogp.me/ns#" class="no-js">
<body>
</header>

    <div class="container">
        <h1><a>Add cost</a></h1>
        <div class="card">

            <div class="card-header"><i class="fa fa-fw fa-plus-circle"></i> <strong>Add cost</strong> <a href="properties.php" class="float-right btn btn-dark btn-sm"><i class="fa fa-fw fa-globe"></i> Browse Costs</a></div>

            <div class="card-body">

                

                <div class="col-sm-6">

                    <h5 class="card-title">Fields with <span class="text-danger">*</span> are mandatory!</h5>

                    <form action="upload.php" method="post" enctype="multipart/form-data"> 

                        <div class="form-group">
                        

                            <label>Description <span class="text-danger">*</span></label>

                            <input type="text" name="description" id="description" class="form-control" placeholder="Description" >

                        </div>

                        <div class="form-group">

                            <label>Location <span class="text-danger">*</span></label>

                            <input type="text" name="location" id="location" class="form-control" placeholder="Cost location"  >

                        </div>

                        <div class="form-group">

                            <label>Cost <span class="text-danger">*</span></label>

                            <input type="number" class="form-control" name="cost" id="cost" placeholder="Enter  property address" >

                        </div>
                        
                        
                        <div class="form-group">
                            <label>Date<span class="text-danger">*</span></label>
                            
                            
                            <input class="form-control" type="date" id="datee" name="datee"/>
                        </div>
                        
                        <div class="form-group">
                            <label for="exampleFormControlSelect1">Category</label>
                            <select class="form-control" id="type" type="text" name="type" >
                            <?php
                                                        
                                //$mysqli = new mysqli('localhost', 'root', '', 'test');
                                                        
                                $query = "SELECT name FROM kategori";
                                $result = mysqli_query($db2, $query);
                                while ($rows = mysqli_fetch_array($result)) {
                                    echo '<option value="' . $rows['name'] . '">' . $rows['name'] . '</option>';
                            }
                            ?> 
                             </select>
                        </div> 

    <div class="input-group">
      <div class="custom-file">
        <input type="file" class="custom-file-input" id="fileToUpload" aria-describedby="customFileInput" name="fileToUpload">
        <label class="custom-file-label" for="customFileInput">Select file</label>
      </div>
      
    </div>
  </div>
    


  <script>
    document.querySelector('.custom-file-input').addEventListener('change', function (e) {
      var name = document.getElementById("fileToUpload").files[0].name;
      var nextSibling = e.target.nextElementSibling
      nextSibling.innerText = name
    })
  </script>
                          <div class="form-group">
                            <button type="submit" name="submit" value="submit" id="submit" class="btn btn-primary"><i class="fa fa-fw fa-plus-circle"></i> Add Cost</button>
                        </div> 

                    </form>

                </div>

            </div>

        </div>

    </div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/jquery.caret/0.1/jquery.caret.js"></script>
    <script src="https://www.solodev.com/_/assets/phone/jquery.mobilePhoneNumber.js"></script>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">


</body>

</html>

这是upload.php

<?php include_once('config.php');
include_once('header.php');
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
// get details of the uploaded file
$fileTmpPath = $_FILES['fileToUpload']['tmp_name'];
$fileName = $_FILES['fileToUpload']['name'];
$fileSize = $_FILES['fileToUpload']['size'];
$fileType = $_FILES['fileToUpload']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
$uploadFileDir = './uploads/';
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
$dest_path = $uploadFileDir . $newFileName;
function if_exist($target_file){
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
      }
}

if(isset($_REQUEST['submit'])){
    
    if(move_uploaded_file($fileTmpPath, $dest_path))
{
    
  $message ='Completed';
  header('location:costs.php?msg=ras');
  echo $message;
}

else
{
    
  $message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.';
  echo $message;
}
}
?>

标签: phphtml

解决方案


我还注意到了几点。

  1. 对于表单提交,它应该代替按钮

  2. $fileName = $_FILES['fileToUpload']['name']; 已经有扩展名了。将扩展名添加到 $newFileName = md5(time() . $fileName) 。'。. $文件扩展名;在其中进行了额外的扩展。

  3. 通过使用 $_POST['description'], $_POST['location'] 值获取输入变量,在 upload.php 中包含您的数据库更新处理


推荐阅读