图片上传无效

时间:2012-04-17 02:04:53

标签: php mysql html file-upload

我真的很想得到你的帮助。 我认为自己是一名中级PHP程序员,但我以前从未使用过文件上传。 我已经坚持这个问题很长一段时间了。 这是我的代码的简化版本,我99%肯定错误在这里的某处。 输出始终是“文件不是图像文件。”

这是我的HTML ...

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" id ="partyPic"><br/>
<button  type="button" onClick="uploadFile()">upload</button>
</form>

这是我的PHP ...

$image = $_FILES['image']['tmp_name'];

if (!isset($image)){

  //Create default image.

}else{

$image =  mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$name = mysql_real_escape_string($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
}

if($image_size == FALSE){
echo 'The file wasn\'t an image file.';
}else{
//I have code that successfully uploads stuff to my database.
}

如果你能提供帮助,我们将不胜感激。

谢谢你, 里克瑞恩

3 个答案:

答案 0 :(得分:1)

http://www.php.net/manual/en/features.file-upload.post-method.php上传示例:

基本表格:

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form> 

PHP:

<?php

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?> 

手册中的示例。

所以你应该建立这样的东西:

<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form> 

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_FILES['userfile']['error'] == 'UPLOAD_ERR_OK'){
    $uploaddir = '/var/www/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
    list($width, $height, $type, $attr) = getimagesize($_FILES['userfile']['tmp_name']);

    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        echo "File was successfully uploaded.\n";
        ... Do Database stuff
    }
}
?>

答案 1 :(得分:0)

您的文件输入ID为partyPic。您应该使用$_FILES['partyPic']

答案 2 :(得分:0)

试试这个:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name ="image" id="partyPic"><br/>
<button  type="button" onClick="uploadFile()">upload</button>
</form>