如何使用 ajax 将图像上传表单的 enctype 数据传输到 php


How to transfer image upload form's enctype data to php using ajax?

我正在尝试使用php和ajax上传图像。我已经尝试过编码,但我不确定如何将要上传的文件的ectype数据传递给AJAX,然后将其传递给PHP,我正在上传文件并将文件的路径保存到数据库中。这是我的 html 和 AJAX 代码。

<form class="form-horizontal" role="form" onsubmit="uploadimage(this.value)" method="post" id= "sample" enctype="multipart/form-data">
            <input type="hidden" name="sid" value="<?php echo $sid; ?>">
            <input type="hidden" name="site" value="<?php echo $site; ?>">
            <input type="hidden" name="img_pos" value="img_gal1">
            <div class="form-group">
                <!--<label class="control-label col-lg-2">Upload Gallery</label><br/>-->
                <div class="col-lg-10">
                    <input type="file" name="fileToUpload" placeholder="Upload Gallery">
                    <!--<input type="Submit" value="Upload Image" name="submit">-->
                </div>
            </div>
            <div class="form-group"> 
                <div class="col-sm-5">
                    <input type="submit" class="btn btn-primary form-control">
                </div>
            </div>
        </form>

而 Ajax 代码是:

<script>
function uploadimage(str) {
  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  } 
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { //   code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","gallery_upload.php?q="+str,true);
  xmlhttp.send();
}

我刚刚从w3schools复制了代码。我不确定关于二维文件数组传递的 ajax 代码应该是什么,所以我没有编辑它。php 代码如下所示以供参考。

<?php
$img_pos= $_REQUEST["img_pos"];
$folder= "img/$sid/";
if (!file_exists($folder)) 
{
     mkdir($folder, 0777, true);
     $target_dir = $folder;
}
else
{
$target_dir = $folder;
}
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$n_filename= $target_dir.$img_pos.".".$imageFileType;
rename($target_file, $n_filename);
$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["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        //echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        //echo "File is not an image.";
        $uploadOk = 0;
    }
}
 /*Check if file already exists
if (file_exists($target_file)) {
    header("Location: admin/pages/profile.php?response= Sorry, file already exists. PLease change the name and try again!&sid=".$sid);
    //echo "Sorry, file already exists.";
    $uploadOk = 0;
}*/
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    header("Location: admin/pages/profile.php?response= Sorry, your file is too large.&sid=".$sid);
    //echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    header("Location: admin/pages/profile.php?response= Sorry, only JPG, JPEG, PNG & GIF files are allowed.&sid=".$sid);
    //echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    header("Location: admin/pages/profile.php?response= Sorry, your file was not uploaded.&sid=".$sid);
    //echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        $query="Update content SET ".$img_pos."='".$_FILES["fileToUpload"]["name"]."' where Sid='".$sid."' and site='".$site."'";
        $result= mysqli_query($con,$query) or die(mysqli_error($con));
        if($result)
        {
            header("Location: admin/pages/profile.php?response= Great! Your Profile has been updated&sid=".$sid);
            //echo "done";
            //echo $query;
        }
        } else {
            header("Location: admin/pages/profile.php?response= Sorry, there was an error uploading your file.&sid=".$sid);
            //echo "Sorry, there was an error uploading your file.";
        }
    }
?>

我想从页面上传 5 张图片。所以我有5种不同的形式。我想使用 AJAX 只制作一个 php 代码来上传图像。所以基本上我想要的是我将文件类型数据传输到 AJAX,然后 AJAX 使用 php 并将图像上传到文件夹并更新数据库中的路径。所以我基本上想知道用 php 发送数据的 AJAX 代码是什么。

您正在检查if(isset($_POST["submit"])) {但没有带有name="submit"的元素

编辑:我没有注意到您实际上有一个GET请求而不是POST请求:xmlhttp.open("POST","gallery_upload.php?q="+str,true);

表单的 enctype 与文件的媒体类型(也称为其 mime 类型(不同,我认为这是您真正想要的。您不能(也不想(依赖从浏览器/客户端传入的媒体类型,而应该在服务器端检查文件的媒体类型,以确认它是有效的(预期的(类型。您可以通过几种不同的方式执行此操作,但以下是使用 mime_content_type 的方法。例:

$upload_file_mime_type = mime_content_type($_FILES["fileToUpload"]["tmp_name"]);

如果上传的文件是PNG类型的合法图像文件,则MIME类型将image/png。如果您只想验证上传的文件是否为图像文件,则可以使用 explode$upload_file_mime_type的字符串值拆分为数组。例:

$upload_file_mime_type_parts = explode("/", $upload_file_mime_type);
if ( $upload_file_mime_type_parts[0] != "image" ) {
     echo "File must be valid image!";
}