简体   繁体   English

如何使用 AJAX 和 PHP 上传图像?

[英]How to upload an image with AJAX and PHP?

I am trying to upload an image and insert to a database alongside the users details as a profile picture.我正在尝试上传图像并与用户详细信息一起作为个人资料图片插入数据库。 The output I currently get is {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} How can I solve this? The output I currently get is {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} How can I solve this? I have also tried to use local storage as this is for a Cordova application.我还尝试使用本地存储,因为这是针对 Cordova 应用程序的。 In the database I have 'Imagename' 'varchar(50)' null = yes在数据库中我有 'Imagename' 'varchar(50)' null = yes

HTML HTML

<img src="img/profilepic.png" alt="profilepic" style="width:200px;height:200px;">
                <form id="imageForm" method="POST" enctype="multipart/form-data" class="imageform">
                    Select image to upload:
                    <input type="file" name="fileToUpload" id="fileToUpload">
                    <input type="submit" value="Upload Image" name="submit">
                </form>

                <p id="error" class="errormessage"></p>
                <p id="image" class="imagemessage"></p>

JS JS

// When upload image button is clicked
$(document).ready(function() {
    var imageform = $("#imageForm");
    $("#imageForm").on('submit', function(event) {
        event.preventDefault();
        var imageValue = document.getElementById("fileToUpload").value; 

        //Set Local Store for Image
        window.localStorage.setItem("fileToUpload", fileToUpload);

        var imageform = new FormData(this);

        var formData = new FormData($('#imageForm')[0]);

            //Get Storage 
                var username = window.localStorage.getItem("username");

                imageform.append('username', username);

                var image = window.localStorage.getItem("fileToUpload");

                //imageform.append('fileToUpload', fileToUpload);

            // Call AJAX    
            $.ajax({
                type: 'POST',
                url: 'image.php',
                data: imageform,
                processData: false, 
                contentType: false,
                success: function(data) {
                    if(data == "Success"){
                        document.getElementById("image").innerHTML = "Image Change Successful";

                        var image = window.localStorage.getItem("fileToUpload");

                            console.log(data); 

                    } else {
                        console.log(data); 
                        document.getElementById("error").innerHTML = "Error Uploading Image";
                    }
                }
            });  
        $("#fileToUpload").on("change", function() {
        $("imageForm").submit();
    }); 
  }); 
});

PHP PHP

<?php
    require_once('checklog.php');
    require_once("functions.php");
    require_once("db_connect.php");

$username = $_POST['username'];
$image = $_POST['fileToUpload'];

session_start(); 
if($_POST['submit'] == "Upload Image"){
    $target_dir = "images/";
    $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) {
            $message = "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            $message = "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        $message = "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        $message = "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        $message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        $message = "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)) {

            $uploadedfilename= basename( $_FILES["fileToUpload"]["name"]);
            $query = "UPDATE users SET imagename='$uploadedfilename' WHERE username='$username'";
            mysqli_query($db_server, $query) or die("Insert failed. ". mysqli_error($db_server)); 
            $message = "<strong>Image $uploadedimage upload successful!</strong>";


        } else {
            $message = "Sorry, there was an error uploading your file.";
        }
    }
}

$currentimagename = "profilepic.png";
$query="SELECT imagename FROM users WHERE username='$username'"; 
$result = mysqli_query($db_server, $query) or die("image load failed. ". mysqli_error($db_server)); 
if($row = mysqli_fetch_array($result)){
    if($row['imagename']<>""){
        $currentimagename = $row['imagename'];
    }   
}
mysqli_free_result($result);

echo $message;

echo json_encode($result);

?>

Hi I think this link will help you and one more change in your database you need to change your datatype is BLOB or varchar size php-ajax-image-upload嗨,我认为此链接将对您有所帮助,并且您需要更改数据类型的数据库中的另一项更改是 BLOB 或 varchar 大小php-ajax-image-upload

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM