如何用php、js和本地存储上传图片?

我以前用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;

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; 
    }); 
}); 

解决方案:

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

enctype=’multipartform-data’。

请在表单标签中添加以下内容,您的代码就能正常工作##标题##。

给TA打赏
共{{data.count}}人
人已打赏
未分类

如何将网络上的数据以照片的形式导入?

2022-9-9 7:31:21

未分类

如何在 While 循环中增加一个整数并将其转换为字符串?

2022-9-9 7:31:23

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索