使用文件名上传图片不能为空

时间:2016-05-23 10:14:25

标签: php mysqli

我正在上传包含上传图片的页面,一切都很好。但是当我意外上传图像而没有选择任何图像时出现问题。出现警告"警告:file_get_contents():文件名不能为空"。我试着解决但警告仍然出现了。我需要添加任何东西吗?我应该怎么做才能删除该警告?这是我的PHP代码

<form name="form1" action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>select files</td>
<td><input type="file" name="f1"></td>
</tr>
<td><input type="submit" name="submit1" value="upload"></td>
<td><input type="submit" name="submit2" value="display"></td>
</table>
</form>

<?php
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con,"image")or die(mysqli_error($con));;
if(isset($_POST["submit1"]))
{
    $image = addslashes(file_get_contents($_FILES['f1']['tmp_name']));
    $sql ="INSERT INTO images (username, image)  VALUES('$_SESSION[username]','$image')";
    $result=mysqli_query($con, $sql);

}if(isset($_POST["submit2"]))
{
    $sql = "SELECT username, image FROM images where username = '$_SESSION[username]' ";
    $result = mysqli_query($con,$sql);
    echo"<table>";
    echo "<tr>";
    while ($row=mysqli_fetch_assoc($result))
    {
        echo "<td>";
        echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'" height="100" width="100"/>';
        echo "</td>";


    }
    echo "</tr>";
}

?>
?>

1 个答案:

答案 0 :(得分:0)

使用此代码

    if(isset($_POST["submit1"]))
            {
   echo  $image=$_POST['f1'];
            if($image)
            {
             $image = addslashes(file_get_contents($_FILES['f1']['tmp_name']));
                $sql ="INSERT INTO images (username, image) VALUES     ('$_SESSION[username]','$image')";
                $result=mysqli_query($con, $sql);

            }
            else

            {

           $msg="Filename cannot be empty";
            echo "<script type='text/javascript'>alert('$msg');</script>";
            }
            }