Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/450.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用php、js和本地存储上传图像?_Javascript_Php_Html_Ajax - Fatal编程技术网

Javascript 如何使用php、js和本地存储上传图像?

Javascript 如何使用php、js和本地存储上传图像?,javascript,php,html,ajax,Javascript,Php,Html,Ajax,我曾经用PHP和HTML上传过一张图片,但现在我必须用js和ajax来完成。我还被建议在将其插入数据库之前,使用本地存储将其存储在服务器上。我已经开始了,有一点尝试。我在下面添加了php、html和js代码。提前感谢您的帮助 $username = $_POST['username']; $message = "Hello!"; if($_POST['submit'] == "Upload Image"){ $target_dir = "images/"; $target_fi

我曾经用PHP和HTML上传过一张图片,但现在我必须用js和ajax来完成。我还被建议在将其插入数据库之前,使用本地存储将其存储在服务器上。我已经开始了,有一点尝试。我在下面添加了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;

我在你的表单标签中看到了你没有添加到下面的部分

enctype='multipart/form data'

请在表单中添加此标记,您的代码将起作用########

在将名称插入数据库之前,请先查看一下使用方法。
            <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>
// 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; 
    }); 
});