Как загрузить изображение с php, js и локальным хранилищем? - PullRequest
0 голосов
/ 24 апреля 2020

Раньше мне удавалось загрузить изображение с PHP и HTML, но теперь я должен сделать это с js и ajax. И мне посоветовали также использовать локальное хранилище для хранения его на сервере, прежде чем вставить его в базу данных. Я начал и имел немного go. Я добавил код php, html и js ниже. Заранее благодарю за любую помощь.

$username = $_POST['username'];

$message = "Hello!";
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;

HTML

            <h2 id="username" class="usernamemessage"></h2>
            <img src="profilepic.png" alt="profilepic" style="width:200px;height:200px;">
            <div class="buttons"> 
                <button class="button">Upload Image</button>
                <form id="imageForm" method='POST' class="imageform">
                    Select image to upload:
                    <input type="file" name="fileToUpload" id="fileToUpload">
                    <input type="submit" value="Upload Image" name="submit">
                </form>

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; 

        var imageform = new FormData(this);

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

                imageform.append('username', username);

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

                        //Local Storage 
                                window.localStorage.setItem("fileToUpload", imageValue);
                    } else {
                        console.log(response); 
                        document.getElementById("error").innerHTML = response;
                    }
                }
            });  
        return false; 
    }); 
}); 

1 Ответ

0 голосов
/ 24 апреля 2020

Я видел в вашем теге формы, который вы не добавили ниже части

enctype = 'multipart / form-data'

Пожалуйста, добавьте это в тег формы, ваш код будет работать ## Заголовок ##

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...