0

如果文件已经存在,如何通过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 

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

4

1 回答 1

1

看来您没有使用 codeingiter 的文件上传类。我建议您使用它,因为它会解决您的问题。

如果您上传一个同名文件,并且在您传递的选项中将覆盖设置为 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);
}
}
?>
于 2013-03-02T16:19:43.337 回答