Ajax和PHP照片文件上传器

时间:2014-05-06 22:45:45

标签: javascript php jquery ajax

我正在尝试使用PHP和Ajax创建小型照片上传器。所以我不是一个php人,我有一些问题,总是Something went wrong with your upload!状态。但是当我将其设置为表单动作时,我有成功的动作。 anyboody可以帮忙吗?

HTML:

<form onsubmit="return submitForm()" method="POST" enctype="multipart/form-data">
    <input type="file" name="pic" id="pic" multiple/>
    <input type="submit" value="Upload" for="pic"/>
</form>

PHP:

<?php

$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');

if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
    exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){

    $pic = $_FILES['pic'];

    if(!in_array(get_extension($pic['name']),$allowed_ext)){
        exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
    }
    if($demo_mode){
        $line = implode('       ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
        file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);

        exit_status('Uploads are ignored in demo mode.');
    }
    if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
        exit_status('File was uploaded successfuly!');
    }
}
exit_status('Something went wrong with your upload!');

function exit_status($str){
    echo json_encode(array('status'=>$str));
    exit;
}
function get_extension($file_name){
    $ext = explode('.', $file_name);
    $ext = array_pop($ext);
    return strtolower($ext);
}
?>

和JS:

function submitForm() {
    console.log("submit event");
    $.ajax({
        type: "POST",
        url: "post_file.php",
        enctype: 'multipart/form-data'
    }).done(function( data ) {
        console.log("PHP Output:");
        console.log( data );
    });
    return false;
}

很多!

1 个答案:

答案 0 :(得分:0)

您无法通过AJAX传输文件数据(无论如何)。它曾经是不可能的,因此使用iframe hacks绕过它,但现在使用HTML5你可以使用FormData来完成它。看看这个:Using HTML5 file uploads with AJAX and jQuery