codeigniter文件上传检查文件大小失败,并显示错误号

时间:2018-11-21 11:02:51

标签: php codeigniter file-upload

我正在尝试上传最大2MB大小的图像。我正在尝试6.44MB的图像来检查测试用例。如果图片大小超过2MB,则上传者应会收到相关消息。 我的表格是:

<?php echo form_open_multipart('Addthepic');?>
<table>
  <tr>
     <td><input type="file" name="image">(Dimension should be 370*234)</td>
     <td><input type="text" name="alt_text" placeholder="Alternate Text"></td>
     <td><input type="text" name="title" placeholder="Title"></td>
     <td><input type="text" name="caption" placeholder="Caption"></td>
     <td><input type="submit" name="submit" class="btn btn-success" value="Add Now"></td>
  </tr>
</table>
<?php echo form_close();?>

我的模型中的代码是:

if(!empty($_FILES['image']['name']) && $_FILES['image']['size']>2097152)
{
    return "<div class='alert alert-danger'>Max 2MB file is allowed for image.</div>";
}
else
{
    var_dump($_FILES['image']);
    $msg.="<div class='alert alert-success'>".$_FILES['image']['error']."</div>";
    $config1=array(
        'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/assets/uploads/eimg/",
        'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
        'overwrite'  => TRUE,
        'file_name' =>$filename
    );
    $this->load->library('upload',$config1);
    $this->upload->overwrite = true;
    if($this->upload->do_upload('image'))
    {
        $image_data =   $this->upload->data();
        $configer1 =  array(
          'image_library'   => 'gd2',
          'source_image'    =>  $image_data['full_path'],
          'maintain_ratio'  =>  FALSE,
          'width'           =>  370,
          'height'          =>  234,
          'overwrite'       =>  TRUE,
          'file_name'       =>  $filename
        );
        $this->image_lib->clear();
        $this->image_lib->initialize($configer1);
        $this->image_lib->resize();
        $this->db->where('sno',$sno);
        $this->db->update('events',array('image'=>$filename));
        if($this->db->affected_rows()>0)
            $msg.= "<div class='alert alert-success'>Image has been uploaded successfully</div>";
    }
}
  

服务器上eimg目录的权限为0777

var_dump提供以下输出:

array(5) { ["name"]=> string(12) "Imgname.JPG" ["type"]=> string(0) "" ["tmp_name"]=> string(0) "" ["error"]=> int(1) ["size"]=> int(0) }

$ _ FILES ['image'] ['error']给出

1

$ _ FILES ['image'] ['size']给出

0

$ _ FILES ['image'] ['name']正确显示文件名

2 个答案:

答案 0 :(得分:1)

根据php docs,错误代码1表示文件超出了设置的服务器上传限制。由于您只想通知用户有关文件大小限制超出此问题的信息,因此您可以使用1来检查您的php代码,如下所示:

if(!empty($_FILES['image']['name']) && ($_FILES['image']['error']==1 || $_FILES['image']['size']>2097152))
{
    return "<div class='alert alert-danger'>Max 2MB file is allowed for image.</div>";
}

在这里,2 MB是您在php.ini中设置的限制或通过php代码中的ini设置的限制。

答案 1 :(得分:0)

您在代码中没有做错任何事情,错误值为1,请参见this

是由于php的限制以及您所能上传图片的最大大小所致。

为向想要上载比模型中定义的尺寸更大的图像的用户显示警告,可以使用jquery进行操作。像这样的东西。

HTML

<input type="file" id="myImage" name="image" />

jQuery

$('#myImage').bind('change', function() {

  //this.files[0].size
  alert(this.files[0].size);

});