如果文件已经存在,如何通过codeigniter获取新生成的文件名

时间:2013-03-02 15:53:37

标签: php codeigniter

如果文件已存在,如何通过codigniter获取新生成的文件名?

我将图像文件插入到我的项目(uploads)文件夹中,并将其名称i.e image.png插入到我的数据库表中。

car.png是我uploads文件夹中存在的图片。如果我再次尝试上传car.png图片,那么目前它会像car1.png一样保存到我的上传文件夹而不替换旧图片。我想获取新的图像名称,即car1.png以保存到我的数据库中,但它实际上保存了我从表单发送的名称,即car.png

获取我使用的文件名

 $img1=$_FILES['img1']['name'];  
 //this gives me the name of file which i am uploading from my form  i.e car.png 

请帮我解决我的问题。请....

1 个答案:

答案 0 :(得分:1)

您似乎没有使用代码服务器上的文件上传类。我建议你使用它,因为它可以解决你的问题。

如果您上传的文件名相同,并且在您传递的选项中将覆盖设置为FALSE,则codeigniter会将 car.png 重命名为 car1.png (或下一个可用的号码)。

然后,如果上传成功,它将返回一个包含与该文件相关的所有数据的数组

Array
(
    [file_name]    => mypic.jpg
    [file_type]    => image/jpeg
    [file_path]    => /path/to/your/upload/
    [full_path]    => /path/to/your/upload/jpg.jpg
    [raw_name]     => mypic
    [orig_name]    => mypic.jpg
    [client_name]  => mypic.jpg
    [file_ext]     => .jpg
    [file_size]    => 22.2
    [is_image]     => 1
    [image_width]  => 800
    [image_height] => 600
    [image_type]   => jpeg
    [image_size_str] => width="800" height="200"
)

正如您所看到的,通过这种方式,您将获得文件的名称,即使它已更改。

您可以在此处详细了解文件上传类以及如何实现它: http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

<强> EDIT2 您必须在视图userfile1,userfile2,userfile3等上命名输入文件     

class Upload extends CI_Controller {

  function __construct()
  {
    parent::__construct();
    $this->load->helper(array('form', 'url'));
  }

  function index()
  {
    $this->load->view('upload_form', array('error' => ' ' ));
  }

  function do_upload(){
   $config['upload_path'] = './uploads/';
   $config['allowed_types'] = 'gif|jpg|png';
   $config['max_size']    = '100';
   $config['max_width']  = '1024';
   $config['max_height']  = '768';

   $this->load->library('upload', $config);
   foreach($_FILES as $key => $value){ 
     if ( ! $this->upload->do_upload($key)){
      $error = array('error' => $this->upload->display_errors());
      $this->load->view('upload_form', $error);
    }else{   
        //This $data is the array I described before
      $data = array('upload_data' => $this->upload->data());
        //So if you this you will get the file name
      $filename = $data['upload_data']['file_name'];
    }
  }
  $this->load->view('upload_success', $data);
}
}
?>