如何在 PHP 8 中使用 Ajax 在服务器上上传文件?

本教程将提供如何在 php 8 中使用 ajax 在服务器上上传文件的示例?如果您对使用 Ajax MySQL 数据库示例的 PHP 8 文件上传有疑问,那么我将给出简单的示例和解决方案。您可以查看如何使用 ajax jQuery PHP 8 和 MySQL 上传文件。此示例将帮助您在 MySQL 教程中使用 PHP 8 上传和存储文件。

本文将为您提供如何使用 PHP 8 将文件插入 MySQL 数据库的简单示例

那么,让我们看看下面的解决方案:

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>How to Upload Files on Server using Ajax in PHP 8?</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card m-auto w-75">
                    <div class="card-header text-center text-white bg-dark">
                        <h4>How to Upload Files on Server using Ajax in PHP 8? - Tuts-Station.com</h4>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-success alert-dismissible" id="success" style="display: none;">
                            <button type="button" class="close" data-dismiss="alert">×</button>
                                File uploaded successfully
                        </div>
                        <form id="submitForm">
                            <div class="form-group">
                                <label><strong>Select File : </strong><span class="text-danger"> *</span></label>
                                <input type="file" class="form-control" name="file" id="file" multiple>
                             <span id="error" class="text-danger"></span><br>    
                            </div>
                            <div class="form-group d-flex justify-content-center">
                                <button type="submit" name="upload" class="btn btn-primary">Upload</button>
                            </div>  
                        </form>         
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(document).ready(function(){
            $("input").prop('required',true);
            $('#file').change(function () {
                var ext = this.value.match(/\.(.+)$/)[1];
                    switch (ext) {
                        case 'txt':
                        case 'pdf':
                        case 'docx':
                        case 'csv':
                        case 'xlsx':
                            $('#error').text("");
                            $('button').attr('disabled', false);
                            break;
                    default:
                        $('#error').text("File must be of type txt,pdf,docx,csv,xlsx.");
                        $('button').attr('disabled', true);
                        this.value = '';
                }
            });
            $("#submitForm").on("submit", function(e){
                e.preventDefault();
                $.ajax({
                    url  :"store.php",
                    type :"POST",
                    cache:false,
                    contentType : false, // you can also use multipart/form-data replace of false
                    processData : false,
                    data: new FormData(this),
                    
                    success:function(response){
                      $("#success").show();
                      $("#success").fadeOut(2800);
                    }
                });
            });
        });
    </script>
</body>
</html>

store.php

<?php 

    if (isset($_FILES['file'])) {
        
        $file_name = $_FILES['file']['name'];    
        $file_size = $_FILES['file']['size'];    
        $file_tmp = $_FILES['file']['tmp_name'];     
        $file_type = $_FILES['file']['type'];        

        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "tests";

        $conn = mysqli_connect($servername, $username, $password, $dbname);

        if (!$conn) {
            die("connection failed:" .mysqli_connect_error());
            echo "connection successfull";
        }
            
        $sql="INSERT INTO posts(file) VALUES('$file_name')";
            
        if ($conn->query($sql)===TRUE) {
            echo " ";
        }else{
            echo "<h5 class='alert alert-primary'>Error :".$sql."<br>".$conn->error."</h5>";
        }
            
        if (move_uploaded_file($file_tmp ,"uploads/".$file_name)) {
            echo "<h5 class='alert alert-primary'>File inserted Successfully!</h5>";
        }else{
            echo "<h5 class='alert alert-primary'>File Was Not inserted!</h5>";
        }
    }
?>

Output: