首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查图片是否上传?AJAX PHP

问如何检查图片是否上传?AJAX PHP
EN

Stack Overflow用户
提问于 2016-12-17 20:59:16
回答 1查看 1K关注 0票数 0

我正试图开发一个web应用程序,在那里你可以创建帖子,并有一个(只是一个)图像,但你不需要有一个,它也可以只是一个文本帖子。这只是一个个人项目,试图使php和ajax变得更好,所以我可能做错了.我想要做的是将表单数据提交给一个php函数,这个函数将决定是否上传它,那么我想要做的是,如果它成功地将图像名发送到另一个函数,将post插入到数据库中,但是如果图像上传没有成功地显示错误。此外,如果它不是成功的,但错误是‘没有图片上传’,继续继续并创建文章无论如何。

这是我到目前为止所拥有的

The jQuery

代码语言:javascript
复制
   $(".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();
                }
            });
        }
    });

});

在进行了一些研究之后,我发现如果这是一个错误,我必须将它作为JSON发送回来,然后在jQuery中检查结果。但是我还没有开始工作..。

代码语言:javascript
复制
<?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会帮你解决这个问题

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-19 02:45:26

你说你想做的和你实际做的不一样。在您的代码中,您正在尝试两个AJAX调用:(1)上传图像,(2)保存post。

为什么不在一个电话里同时做两件事呢?这样,您就不必等待上传图片(或无)的响应才能创建新的帖子。

代码语言:javascript
复制
$(".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中的逻辑与当前代码合并。我通常是这样做的:

代码语言:javascript
复制
// 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 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41203004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档