在PHP中上传文件时发生未知错误

时间:2018-06-21 03:56:54

标签: javascript php jquery ajax

我正在尝试建立一个具有多媒体和文本内容的简单新闻网站。我想同时显示文字和一张图片。我对服务器上的图像进行所有处理。这是jQuery代码。当用户选择文件时,我会运行AJAX请求以检查图像的完整性。我使用来自服务器的JSON响应。

$(document).ready( function () {
$('#iurl').change( function () {
    var formData = new FormData();
    formData.append('iurl', $('input[type=file]')[0].files[0]);
    $.ajax({
        type: 'POST',
        contentType: false,
        cache: false,             
        processData:false,
        url: '/newsapp/php/imgCheck.php',
        data: formData,
        success: function (data) {
          var res = JSON.parse(data);
          $('#errormsg').show();
          $('#errormsg').html(res.info);
          if( res.e == 1 ) {
            $('#getInfo').show();           
          } 
        }
    });           
});});

现在这是PHP代码。

<?php	
  $uploadOK = 1;
  $target_dir = 'newsapp/imgsrc/';
  $fileInfo = pathinfo($_FILES['iurl']['name']);
  $imgFileType = $fileInfo['extension'];
  $target_file = $target_dir . $fileInfo['basename'];
  $check = getimagesize($_FILES['iurl']['tmp_name']);
  $errormsg = '';
 
  if($check === false ) {
    $uploadOK = 0;
    $errormsg = 'Sorry, File is not an image!';
  } elseif (file_exists($target_file)) {
      $errormsg = 'Sorry, image already exsists!';
      $uploadOK = 0;
  } elseif ($_FILES['iurl']['size'] > 4194304 ) {
      $errormsg = 'Sorry, image size too large!';
      $uploadOK = 0;
  } elseif ($imgFileType != 'jpg' && $imgFileType != 'png' && $imgFileType != 'jpeg' ) {
      $uploadOK = 0;
      $errormsg = '.' . $imgFileType . 'extension not supported!';
  } else {
  	  if( $uploadOK ) {
        if( !move_uploaded_file($_FILES['iurl']['tmp_name'], $target_file) ) {
      	  $uploadOK = 0;
          $errormsg = 'Sorry, unknown error while uploading the image';
        }
        else {
      	  $errormsg = 'Image is uploaded!';
        }
      }  
  }

  /* Here some JSON code */
?>

仅在最后一步中,它不会将文件移动到所需位置。救命!

HTML代码

<!DOCTYPE html>
<html>
<head>
	<title>WriteNews</title>
	<link rel="stylesheet" type="text/css" href="/newsapp/css/create.css">
	<script src='/newsapp/scripts/jquery-3.3.1.js'></script>
	<script src='/newsapp/scripts/create.js'></script>
</head>
<body>
	<form enctype='multipart/form-data'>
      <div style='margin-left: 5%;'>
        Image<br><input type='file' id='iurl'/><br/>	
        <div id='getInfo'>
	      Author<br/><input type='text' id='auth' required='Author cannot be left empty'/><br/>
	      Title<br/><input type='text' id='mhead' required='Title cannot be left empty'/><br/>
	      Description<br><input type='text' id='full' required='Description cannot be left empty'/><br/> 
	      <button id='submt'>Submit</button>
        </div>
	  </div>
	</form>      
	<div>
		<p id='errormsg'></p>
	</div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

在您的php.ini文件中,确保最大文件上传大小大于2MB

Maximum allowed size for uploaded files. 
http://php.net/upload-max-filesize
upload_max_filesize=8M

html代码:

<form action="" method="post" enctype="multipart/form-data">
    <!-- Heading -->
    <input type="text" id="heading" name="heading" placeholder="News Heading" required><br>     
    <!-- Image -->
    <input id="image" type="file" name="image"><br>             
    <!-- submit -->
    <input type="submit" name="submit_post" value="Submit">
</form>

php代码:

<?php 
if(isset($_POST["submit_post"])) {
$uploadOk = 1;
$heading= $_POST['heading'];

$post_image = $_FILES['image']['name'];
$target_file="";

if ($post_image != "") {        
    $target_dir = "img/";
    $target_file = $target_dir .uniqid().basename($post_image);
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

        // Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["image"]["tmp_name"]);
    if($check !== false) {
        //echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        //echo "File is not an image.";
        $uploadOk = 0;
    }

    // Check file size
    if ($_FILES["image"]["size"] > 4000000) {
        echo "Sorry your file is too large";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType 
    != "jpeg" && $imageFileType != "gif" ) {
        echo "Sorry, only jpeg, jpg and png files are allowed";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk) {
        if (move_uploaded_file($_FILES["image"]["tmp_name"], 
    "../".$target_file)) {
            echo "The file ". basename( $post_image). " has been uploaded.";

        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

    // INSERT query
    $query=mysqli_query($con, "INSERT INTO news VALUES('$id', 
   '$heading','$post_image')");
   }
   ?>