PHP图像上载不会将图像上载到目标目录

问题描述 投票:1回答:1

Problem:

我创建了一个upload.php文件,其中包含一个HTML表单和上传图像所需的PHP代码,我使用XAMPP localhost:

htdocs/web2/assets/upload.php

我想将图像上传到同一目录中的upload文件夹:

htdocs/web2/assets/uploads/

Script:

    <?php 

        <form action="?" method="post" enctype="multipart/form-data">   

            <!--wrap input button as around pre-existing image -->   
            <?php
                echo '<label class="profile_gallery_image_in"><input type="file" name="fileToUpload" id="fileToUpload" onchange="form.submit()"/><p class="label"></p><img class="myImg" src='.$image.' height="100%" width="100%" /></label>';
            ?>

        </form>

    <!-- Commence Photo Upload -->

    <?php
        $target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
        // Check if image file is a actual image or fake image
        if(isset($_POST["submit"])) {
            $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
            if($check !== false) {
                echo "File is an image - " . $check["mime"] . ".";
                $uploadOk = 1;
            } else {
                echo "File is not an image.";
                $uploadOk = 0;
            }
        }
    ?>

表单设置为在输入类型更改时自动提交。这似乎工作正常,表单正在提交。

但是,我没有上传任何实际图像,也没有任何错误。

我该如何解决这个问题?

php image upload photo
1个回答
0
投票

代码中似乎有错误。您可以使用以下代码进行图片上传。

<?php
   if(isset($_FILES['image'])){
      $errors= array();

      $dir = "images/";
      $file_name = $_FILES['image']['name'];
      $file_name = $dir. $file_name;
      $file_size = $_FILES['image']['size'];
      $file_tmp = $_FILES['image']['tmp_name'];
      $file_type = $_FILES['image']['type'];
      $tmp = explode('.',$_FILES['image']['name']);
      $file_ext=strtolower(end($tmp));
      
      $extensions= array("jpeg","jpg","png","gif");
      
      if(in_array($file_ext,$extensions)=== false){
         $errors[]="extension not allowed, please choose a GIF, JPEG or PNG file.";
      }
      
      if($file_size > 2097152) {
         $errors[]='File size must be excately 2 MB';
      }
      
      if(empty($errors)==true) {
         move_uploaded_file($file_tmp, $file_name);
         echo "Success";
      }else{
         print_r($errors);
      }
   }
?>
<html>
   <body>
      
      <form action = "" method = "POST" enctype = "multipart/form-data">
         <input type = "file" name = "image" />
         <input type = "submit"/>
      </form>
      
   </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.