簡體   English   中英

如何查看圖片是否上傳? AJAX PHP

[英]How To Check If Image Uploaded? AJAX PHP

我正在嘗試開發一個Web應用程序,在該應用程序中您可以創建帖子並帶有一個(只有一個)圖像,但是您不必一個,它也可以只是一個文本帖子。 這只是一個個人項目,嘗試使用php和ajax使其變得更好,所以我可能做錯了...我想要做的是在提交時將表單數據發送到php函數,該函數將確定是否上傳它或否,那么我想做的是,如果成功,則將圖像名稱發送到其他函數以將帖子插入數據庫,但是如果圖像上傳不成功,則顯示錯誤。 另外,如果未成功,但錯誤是“未上傳圖片”,請繼續創建帖子。

這是我到目前為止的

jQuery的

   $(".new-post").submit(function (e) {

    e.preventDefault();

    $.ajax({
        type: "post",
        url: "includes/image-upload.php",
        data: new FormData(this),
        processData: false,
        contentType: false,
        error: function (response) {
            console.log(response);
        },
        success: function (response) {
            var body = $("#post-body").val();
            $.ajax({
                type: "post",
                url: "create-post-feed.php",
                data: {
                    body: body,
                    image: response
                },
                error: function (response) {
                    console.log(response);
                },
                success: function (response) {
                    //                        console.log(response);
                    $('section.feed').prepend(response);
                    $('article.post p').each(function () {
                        $(this).html(linkHashtags($(this).html()));
                    });
                    $('article.post p').each(function () {
                        $(this).html(linkatsymbols($(this).html()));
                    });
                    revealPosts();
                }
            });
        }
    });

});

PHP經過一番研究后,我發現如果是錯誤,我必須將其作為JSON發送回去,然后在jQuery中檢查結果。 但是我還沒有開始工作...

<?php

require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');

function uploadFile ($file_field = null, $check_image = false, $random_name = false) {

//Config Section 
$user_id = $_SESSION['user_id'];
//check if directory exist if not create it
if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
    mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
}
if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
    mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
}
//Set file upload path
$path = "../users/user_".$user_id."/posts/"; //with trailing slash
//Set max file size in bytes
$max_size = 1000000;
//Set default file extension whitelist
$whitelist_ext = array('jpeg','jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');

//The Validation
// Create an array to hold any output
$out = array('error'=>null);

if (!$file_field) {
    $out['error'][] = "Please specify a valid form field name";           
}

if (!$path) {
    $out['error'][] = "Please specify a valid upload path";               
}

if (count($out['error'])>0) {
    return $out;
}

//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {

    // Get filename
    $file_info = pathinfo($_FILES[$file_field]['name']);
    $name = $file_info['filename'];
    $ext = $file_info['extension'];

    //Check file has the right extension           
    if (!in_array($ext, $whitelist_ext)) {
        $out['error'][] = "Invalid file Extension";
    }

    //Check that the file is of the right type
    if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
        $out['error'][] = "Invalid file Type";
    }

    //Check that the file is not too big
    if ($_FILES[$file_field]["size"] > $max_size) {
        $out['error'][] = "File is too big";
    }

    //If $check image is set as true
    if ($check_image) {
        if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
            $out['error'][] = "Uploaded file is not a valid image";
        }
    }

    //Create full filename including path
    if ($random_name) {
        // Generate random filename
        $tmp = str_replace(array('.',' '), array('',''), microtime());

    if (!$tmp || $tmp == '') {
        $out['error'][] = "File must have a name";
    }     
        $newname = $tmp.'.'.$ext;                                
    } else {
        $newname = $name.'.'.$ext;
    }

    //Check if file already exists on server
    if (file_exists($path.$newname)) {
        $out['error'][] = "A file with this name already exists";
    }

    if (count($out['error'])>0) {
        //The file has not correctly validated
        return $out;
    } 
    if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
        echo $newname;
    } else {
        $out['error'][] = "Server Error!";
    }
 } else {
    $out['error'][] = "No file uploaded";
    return $out;
 }      
}

$file = uploadFile('file', true, true);

if (is_array($file['error'])) {
echo json_encode($file['error']);
}

die();

非常感謝您提供任何有關如何使其更好的幫助或意見。BTW目前有效,唯一的問題是無論是否上傳圖片,總是創建帖子。

通常我至少會在同一天得到答案...這個問題不好嗎? 我聽說編輯XD有助於“解決問題”

您說的想做的與您實際做的不同。 在您的代碼中,您正在嘗試兩次AJAX調用:(1)上傳圖片和(2)保存帖子。

為什么不在一次通話中同時做兩件事呢? 這樣,您不必等待上傳圖像的響應(或沒有響應)來創建新帖子。

$(".new-post").submit(function (e) {
    e.preventDefault();
    $.ajax({
        type: "post",
        url: "create-post-feed.php",
        data: new FormData(this), // send post information including selected file
        processData: false,
        contentType: false,
        error: function (response) {
            console.log(response);
        },
        success: function (response) {
            // etc
        }
    });
});

然后在您的create-post-feed.php ,將image-upload.php的邏輯與當前代碼合並。 我通常這樣做:

// validate post

// validate image (if any)

// if no errors:

    // upload image (if any) and retrieve filename

// if no errors:

    // save post (with filename if any); if it fails, delete image (if any)

// send response 

@Mikey這就是我新的php文件的樣子。 現在我的問題是,如何做到這一點,以便如果使用jQuery成功,則將新帖子追加到Feed中;如果不成功,則在單獨的div中顯示錯誤?

<?php
require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');

$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];

if( empty($_FILES[$image]['name']) ){
    $has_image = 0;
}else{
    $has_image = 1;
}

$postEmpty = 0;

if( empty($_FILES[$image]['name']) && empty($body) ){
$postEmpty = 1;
die();
} 

// validate post

if( $postEmpty == 0 && !empty($body) ){

    $cleanBody = clean_input($body);

}

// validate image (if any)

if( $has_image == 1 ){

    //check if directory exist if not create it
    if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
        mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
    }
    if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
        mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
    }
    //Set file upload path
    $path = "../users/user_".$user_id."/posts/"; //with trailing slash
    //Set max file size in bytes
    $max_size = 2000000;
    //Set default file extension whitelist
    $whitelist_ext = array('jpeg','jpg','png','gif');
    //Set default file type whitelist
    $whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');

    // Create an array to hold any output
    $errors = array();

    // Get filename
    $file_info = pathinfo($_FILES[$image]['name']);
    $name = $file_info['filename'];
    $ext = $file_info['extension'];

    //Check file has the right extension           
    if (!in_array($ext, $whitelist_ext)) {
        $errors[] = "Invalid file Extension";
    }

    //Check that the file is of the right type
    if (!in_array($_FILES[$image]["type"], $whitelist_type)) {
        $errors[] = "Invalid file Type";
    }

    //Check that the file is not too big
    if ($_FILES[$image]["size"] > $max_size) {
        $errors[] = "File is too big";
    }

    //If $check image is set as true
    if (!getimagesize($_FILES[$image]['tmp_name'])) {
        $errors[] = "Uploaded file is not a valid image";
    }

    //Create full filename including path
    if ($random_name) {
    // Generate random filename
        $tmp = str_replace(array('.',' '), array('',''), microtime());

    if (!$tmp || $tmp == '') {
        $errors[] = "File must have a name";
    }     
        $newname = $tmp.'.'.$ext;                                
    } else {
        $newname = $name.'.'.$ext;
    }

    //Check if file already exists on server
    if (file_exists($path.$newname)) {
        $errors[] = "A file with this name already exists";
    }

    if (count($errors)>0) {
    //The file has not correctly validated
        $imageError = 1;
    }

// if no errors:

    // upload image (if any) and retrieve filename
    if( $imageError == 1 ){

        foreach($errors as $error) {
            echo '<li>'.$error.'</li>';
            die();
        }

    }else{

        //Create full filename including path
        // Generate random filename
        $tmp = str_replace(array('.',' '), array('',''), microtime());

        if (!$tmp || $tmp == '') {
            $errors[] = "File must have a name";
        }     

        $newname = $tmp.'.'.$ext;                                

        //Check if file already exists on server
        if (file_exists($path.$newname)) {
            $errors[] = "A file with this name already exists";
        }

        if (count($errors)>0) {
        //The file has not correctly validated
            $imageError = 1;
            foreach($errors as $error) {
                echo '<li>'.$error.'</li>';
                die();
            }
        } 
      if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {

            $uploadSuccesfull = 1;

        }else {
            $errors[] = "Server Error!";
            foreach($errors as $error) {
                echo '<li>'.$error.'</li>';
                die();
            }
        }

    }
}


// if no errors:

// save post (with filename if any); if it fails, delete image (if any)
if( $has_image == 1 ){

$query = "INSERT INTO posts
        (user_id, body, image, has_image, date)
        VALUES
        ('$user_id', '$body', '$newname', '$has_image', now())";

}else{

    $query = "INSERT INTO posts
        (user_id, body, has_image, date)
        VALUES
        ('$user_id', '$body', '$has_image', now())";

}

$result = $db->query($query);

// send response

//check to make sure the user was added
if( $db->affected_rows == 1 ){

    $user_id = $_SESSION['user_id'];

    $post_id = $db->insert_id;

    $query = "SELECT post_id, body, image, has_image
            FROM posts
            WHERE post_id = $post_id
            LIMIT 1";
    $result = $db->query($query);

    if($result->num_rows == 1){
        $row = $result->fetch_assoc();
    }

    $queryuser = "SELECT *
                FROM users
                WHERE user_id = $user_id
                LIMIT 1";
    $resultuser = $db->query($queryuser);
    if($resultuser->num_rows == 1){
        $rowuser = $resultuser->fetch_assoc();
    }


 if(!empty($row['avatar'])){ $userpic = $row['avatar']; }else{ $userpic = HOME_URL . 'img/avatar.jpg'; }

    if($row['has_image'] == 1){

?>
<article class="post">
    <div class="post-head cf">
        <a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
        <a href="" class="username">
            <?php echo $rowuser['username']; ?>
        </a>
    </div>
    <img src="users/user_<?php echo $rowuser['user_id'] ?>/posts/<?php echo $row['image']; ?>" alt="">
    <div class="post-body">
        <div class="post-options">
            <a class="likes" href="">156 likes</a>
        </div>
        <p>
            <a class="username" href="">
                <?php echo $rowuser['username'] ?>
            </a>
            <?php echo $row['body'] ?>
        </p>
        <hr />
        <div class="cf">
            <a class="like hide-text" href="javascript:;">Like This Post</a>
            <form action="" class="comment">
                <input type="text" placeholder="Add a comment">
            </form>
        </div>
    </div>
</article>
<?php }else{ ?>

    <article class="post no-img">
        <div class="post-head cf">
            <a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
            <a href="" class="username">
                <?php echo $rowuser['username'] ?>
            </a>
        </div>
        <div class="post-body">
            <p>
                <a class="username" href="">
                    <?php echo $rowuser['username'] ?>
                </a>
                <?php echo $row['body'] ?>
            </p>
            <div class="post-options">
                <a class="likes" href="">1 like</a>
            </div>
            <hr />
            <div class="cf">
                <a class="like hide-text" href="javascript:;">Like This Post</a>
                <form action="" class="comment">
                    <input type="text" placeholder="Add a comment">
                </form>
            </div>
        </div>
    </article>

    <?php }
    }else{

        echo 'There was a database error';

     }

die();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM