【问题标题】:PHP - Checking for Uploaded ImagePHP - 检查上传的图像
【发布时间】:2015-02-17 18:37:38
【问题描述】:

我对 PHP 比较陌生,需要一些帮助查看 1. 如果已上传图像以供提交并完成一组提交 ELSE 如果尚未上传图像,则提交一组不同的 sql 信息。

我之前尝试过 isset()、is_uploaded_file() 和 file_exists(),但似乎无法发送任何内容。

HTML 表单

           <form method="POST" action="php/editInv.php" enctype="multipart/form-data" id="editInv">
           <table>
              <tbody>
              <?php
                 $productId = $_GET['productId'];

                 require ('php/dbcon.php');

                 $con=mysqli_connect(HOST,USER,PASS,DB);

                 $sqlId = "SELECT * FROM products WHERE productId='".$productId."'";

                 $sqlIdResult = mysqli_query($con,$sqlId);

                 while($rowId=mysqli_fetch_array($sqlIdResult)) {
              ?>
                 <tr>
                    <td>
                       <label for="productName">Product Name: </label>
                    </td>
                    <td>
                       <input name="productName" id="productName" type="text" value="<?php echo $rowId['productName']; ?>"/>
                       <input name="prodId" id="prodId" type="hidden" value="<?php echo $rowId['productId']; ?>" />
                    </td>
                    <td>
                       <label for="productDesc">Product Description: </label>
                    </td>
                    <td rowspan="4">
                       <textarea name="productDesc" id="productDesc" cols="55" rows="10"><?php echo $rowId['productDesc']; ?></textarea>
                    </td>
                 </tr>
                 <tr>
                    <td>
                       <label for="gender">Gender: </label>
                    </td>
                    <td>
                       <select name="gender" id="gender">
                          <option id="1" value="1">Male</option>
                          <option id="2" value="2">Female</option>
                          <option id="3" value="3">Unisex</option>
                       </select>
                       <input type="hidden" value="<?php echo $rowId['genderId']; ?>" id="genderHid"/>
                       <script>
                          var gender=$('#genderHid').val();
                          var selected=$('#gender').find('#'+gender);
                          $(selected).attr('selected','selected');
                       </script>
                    </td>
                 </tr>
                 <tr>
                    <td>
                       <label for="inventory">Inventory: </label>
                    </td>
                    <td>
                       <input type="number" name="inventory" id="inventory" value="<?php echo $rowId['inventory']; ?>"/>
                    </td>
                 </tr>
                 <tr>
                    <td>
                       <label for="price">Price: </label>
                    </td>
                    <td>
                       $<input type="text" name="price" id="price" value="<?php echo $rowId['price']; ?>" />
                    </td>
                 </tr>
                 <tr>
                    <td>
                       <label for="productImage">Upload Image: </label>
                    </td>
                    <td>
                       <input type="file" name="productImage" id="productImage" />
                    </td>
                    <td colspan="2">
                       <div id="progress" style="width:100%;">
                          <div id="bar" style="height:50px;background-color:blue;width:0%;">
                          </div>
                          <p id="percent"></p>
                       </div>
                    </td>
                 </tr>
                 <tr>
                    <td colspan="2" rowspan="2">
                       <img id="prevImage" style="" src="<?php echo $rowId['productImage']; ?>" />
                    </td>
                    <td id="response">

                    </td>
                    <td>
                       <button type="submit" id="editInv">Edit Item</button>
                    </td>
                 </tr>
                 <tr>
                 </tr>
              <?php
              };
              ?>
              </tbody>
           </table>
           </form>

AJAX

  var options = {
  beforeSubmit: function() {
     // pre submit callback
     $("#progress").show();
     $("#percent").html("0%");
  },
  data: {
     productName : $('#productName').val(),
     productDesc : $('#productDesc').val(),
     inventory : $('#inventory').val(),
     price : $('#price').val(),
     gender : $('#gender').val(),
     image : $('#prevImage').attr('src'),
     prodId : $('#prodId').val()
  },
  uploadProgress: function(event, position, total, percentComplete) {
     //during submission
     $("#bar").width(percentComplete+'%');
     $("#percent").html(percentComplete+'%');
  },
  success: function(msg) {
     //post submit call back
     $(".bar").css("width","100%");
     $(".percent").html('100%');
     $("#response").html(response.responseText);
  },
  complete: function(response) {
     if(response.responseText=="Invalid File"){
     } else {
        $("#response").html(response.responseText);
        //$("#addNew")[0].reset();
        //$("#prevImage").attr('src','').hide();
        $(".bar").css("width","0%");
        $(".percent").html('0%');
     }

  },
  error: function(response) {
     alert(response.responseText);
  }

};

$("#editInv").ajaxForm(options);

PHP

//If a file has been uploaded
if (!empty($_FILES["productImage"]["name"])) {

 $target_dir = $_SERVER['DOCUMENT_ROOT'] . "/images/inventory/";
 $target_file = $target_dir . basename($_FILES["productImage"]["name"]);
 $fileName = str_replace(' ', '', $productName);
 $target_file_insert = "/images/inventory/" . $fileName . ".jpg";
 $targetFileUpload = $target_dir . $fileName . ".jpg";


 $sql1 = "UPDATE products SET productName='".$productName."', productDesc='".$productDesc."', inventory='".$inventory."', price='".$price."', genderId='".$gender."', productImage='".$targetFileUpload."' WHERE productId='".$prodId."'";

 mysqli_query($con,$sql1);

 $uploadOk = 1;
 $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
 // Check if image file is a actual image or fake image
 if(isset($_POST["submit"])) {
     $check = getimagesize($_FILES["productImage"]["tmp_name"]);
     if($check !== false) {
         echo "File is an image - " . $check["mime"] . ".";
         $uploadOk = 1;
     } else {
         echo "File is not an image.";
         $uploadOk = 0;
     }
 }
 // Allow certain file formats
 if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "JPG" && $imageFileType != "JPEG") {
     echo "Sorry, only JPG, and JPEG files are allowed.";
     $uploadOk = 0;
 }
 // Check if $uploadOk is set to 0 by an error
 if ($uploadOk == 0) {
     echo "Sorry, your file was not uploaded.";
 // if everything is ok, try to upload file
 } else {
     if (move_uploaded_file($_FILES["productImage"]["tmp_name"], $targetFileUpload)) {
         mysqli_close($con);
     } else {
         echo "Sorry, there was an error uploading your file.";
     }
 }
} else
//If a file has not been uploaded
/*if (empty($_FILES["productImage"]["name"])) */{
  $sql2="UPDATE products SET productName='".$productName."', productDesc='".$productDesc."', inventory='".$inventory."', price='".$price."', genderId='".$gender."', productImage='".$image."' WHERE productId='".$prodId."'";

  mysqli_query($con,$sql2);
}

【问题讨论】:

  • 您的 AJAX 代码中至少存在两个问题:1)您发布了一个选项对象,但没有实际调用 AJAX; 2) 即使您确实发送了这个,您的代码也只发送图像的 src 属性,而不是图像本身,因此您的 PHP 脚本中的 $_FILES 数组将为空。
  • SRC 是一个占位符,当没有图片上传时,它将提交最初从数据库中提取的 SRC。我正在检查是否有新的上传文件。如果没有新上传的文件,那么 $_FILES 应该与 SRC 变量没有任何关系。对 ajax 的调用位于脚本下方,$("#editInv").ajaxForm(options);更新了代码中的调用
  • fyi,我并没有尝试在这里发布我的所有 HTML 元素,但是 $_FILES["productImage"] 调用 HTML 中的文件类型输入,而 src 指向 PHP在页面上生成IMG标签。
  • 您没有将图像附加到 AJAX 调用中,或者如果您选择不发布它。仅在 HTML 中输入文件类型是不够的。
  • 在原始提交页面中,我不使用调用来发布图像。它位于表单内部。根据我对 jQuery AJAX 调用的理解,这就是 $_FILES["productImage"] 应该从表单中提取的内容。因此,如果我正在提交并且尚未上传图像,它应该返回 NULL,即第二个 if 语句,但没有运行该查询。

标签: php ajax


【解决方案1】:

您需要检查的路径是$targetFileUpload 而不是$upload

一旦上传检查:

if (!file_exists($targetFileUpload)){...}

【讨论】:

  • 好吧,我可能解释错了。在这一点上,我没有在后端检查任何东西。如果用户没有选择上传新照片,我只需要 php 发送一个查询,如果用户想要使用数据库中已经存在的图像条目,则需要发送另一个查询。我已经在入口页面中进行了验证,因为我使用 php 将我的文件重命名为产品名称,然后再保存它们 perm。到服务器。不过感谢您的回复。
  • if the user didn't choose to upload a new photo,@MarvinWordWeaverParsons 是什么意思
  • 好的,这是一个编辑页面,它会根据 productId SELECT 自动填充数据库中先前条目的数据。因此页面会自动填充产品名称、价格、库存、描述、性别和指向该条目的当前图像的 URL。这使用户能够选择不同的图像,或者保留他们当前拥有的图像并仅更新信息。所以页面上应该已经有一个图像(#prevImage)。如果用户想将此图像用于 UPDATE,则 $_FILES 中不应有条目,发送 NULL。
【解决方案2】:

好吧,它实际上是由两个不同的问题引起的,一个在 PHP 中,另一个在 JavaScript 中调用变量的顺序。除了在页面顶部使用 jQuery 生成的图像作为全局变量之外,我必须调用所有内容,然后使用表单操作调用将 jQuery AJAX 放在页面底部。

显然,使用 jQuery 调用页面底部字段的值会导致它们从后端发送页面填充的信息,而将它们放置在页面顶部会导致它们中继更改后的输入数据到 AJAX 调用。

任何解释为什么会这样?

  <script>
      var productName = $('#productName').val();
      var productDesc = $('#productDesc').val();
      var inventory = $('#inventory').val();
      var price = $('#price').val();
      var gender = $('#gender').val();
      var prodId = $('#prodId').val();
  </script>

//你所有的 HTML 内容

<script>
  var options = {
  beforeSubmit: function() {
     // pre submit callback
     $("#progress").show();
     $("#percent").html("0%");
  },
  data: {
     productName : productName,
     productDesc : productDesc,
     inventory : inventory,
     price : price,
     gender : gender,
     image : $('#prevImage').attr('src'),
     prodId : prodId
  },
  uploadProgress: function(event, position, total, percentComplete) {
     //during submission
     $("#bar").width(percentComplete+'%');
     $("#percent").html(percentComplete+'%');
  },
  success: function(msg) {
     //post submit call back
     $(".bar").css("width","100%");
     $(".percent").html('100%');
     $("#response").html(response.responseText);
  },
  complete: function(response) {
     if(response.responseText=="Invalid File"){
     } else {
        $("#response").html(response.responseText);
        //$("#addNew")[0].reset();
        //$("#prevImage").attr('src','').hide();
        $(".bar").css("width","0%");
        $(".percent").html('0%');
     }

  },
  error: function(response) {
     alert(response.responseText);
  }

};


$("#editInv").ajaxForm(options);
  </script>

PHP if 语句本质上是这样的:

if (!empty($_FILES["productImage"]["name"])) {
} else
//If a file has not been uploaded
if (empty($_FILES["productImage"]["name"])) {
}

感谢@fred-ii- 提供错误捕获器。

【讨论】:

    猜你喜欢
    • 2012-03-08
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 2016-10-06
    • 2013-07-03
    • 1970-01-01
    相关资源
    最近更新 更多