Codeigniter图片上传只会上传到一个目录

时间:2010-12-24 19:53:53

标签: php codeigniter upload

function upload($path){
  $config['overwrite'] = TRUE;
  $config['allowed_types'] = 'jpg|jpeg|gif|png';
  $config['max_size'] = 2000;

  if($path =='profile'){
   $config['upload_path'] = '../assets/uploads/avatars';
   $config['file_name'] = $this->id;  
  }
  if($path =='company'){
   $config['upload_path'] = '../assets/uploads/company';
   $config['file_name'] = $this->id.'_company';
  }

  $this->load->library('upload', $config);
  $this->upload->do_upload();

  $image_data = $this->upload->data();
  if($path == 'profile'){
   $this->db->update('be_user_profiles',array('avatar' => $image_data['file_name']), array('user_id' => $this->id));
  }
  if($path == 'company'){
   $this->db->update('be_user_profiles',array('company_logo' => $image_data['file_name']), array('user_id' => $this->id));
  }
  $config = array(
   'source_image' => $image_data['full_path'],
   'new_image' => $this->upload_path,
   'maintain_ratio' => true,
   'width' => 500,
   'height' => 500
  );

  $this->load->library('image_lib', $config);
  $this->image_lib->resize();
 }

这是我的上传功能,它在$path = 'profile'时工作正常,但当它为company时,它不会上传到“公司”文件夹... 有什么理由应该这样吗?!我在这里不知所措...这个功能在进入头像文件夹时有效,但如果它进入公司文件夹则不行......

5 个答案:

答案 0 :(得分:7)

我在多个文件夹中遇到了类似的问题。我修复的方法是使用初始化函数,而不是将配置作为参数传递给加载库函数。

$this->upload->initialize($config);

您可以加载库然后设置您的配置并调用initialize方法。

希望这有帮助。

答案 1 :(得分:2)

我认为所有建议都非常好,您还可以确保在表单中发布正确的数据:  $这 - > upload-> do_upload();默认情况下,期望表单名称为“userfile”

我发现有时候显示出一些错误非常有用......所以不要只是$this->upload->do_upload();尝试类似

的内容
if (!$this->upload->do_upload($userfile)) {
            $error = array('error' => $this->upload->display_errors());

            $this->load->view('upload_error', $error);
        }

然后在您的视图中添加一个名为upload_error.php的文件,其中包含以下代码:

<html>
<head>
<title>Upload Form</title>
</head>
<body>

<?php echo $error;?>



</body>
</html>
祝你好运!

答案 2 :(得分:2)

尝试在设置此类其他配置之前取消设置配置。 以下代码取消设置配置和清除图像库。

你需要清除你的lib。

//Unset config for the next one
  unset($config);
  $this->image_lib->clear();

来自CI手册......

$this->image_lib->clear()

clear函数重置处理图像时使用的所有值。如果您在循环中处理图像,则需要调用此方法。

答案 3 :(得分:0)

嗯,这是两个建议:

  1. 确保您的company文件夹可写
  2. $this->id返回什么?如果它返回带有扩展名的文件名,那么这就是导致上传过程失败的原因,因为那时你的文件名my_image.png_company不是允许的类型。
    有关详细信息,请参阅documentation page

答案 4 :(得分:0)

 $config = array(
    'upload_path'   './assets/upload/profilepic/',
    'allowed_types' => 'JPG|JPEG|PNG',
    'overwrite' => TRUE,
    'file_name'  => date('YmdHis').''.rand(0,9999)
); 

不适用于JPEG文件类型 我也写过小后者,但没有用。 如果有什么请分享 无法上传JPEG文件。可以轻松插入其他文件。

相关问题