2014-02-16 77 views
19

我想添加时间作为图像名称的前缀以及上传时的原始名称,但我无法弄清楚。上传时,请帮助我使用以下代码在我的原始文件名称中添加前缀。Codeigniter重命名文件上传

<?php 

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'] = 'Public/uploads/'; 
     $config['allowed_types'] = 'gif|jpg|png'; 
     $config['max_size'] = '1024'; 
     $config['max_width'] = '1024'; 
     $config['max_height'] = '768'; 



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


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

      $this->load->view('upload_form', $error); 
     } 
     else 
     { 
      $data = array('upload_data' => $this->upload->data()); 

      $this->load->view('upload_success', $data); 
     } 
    } 
} 
?> 
+1

的[重命名CI中上传的文件(可能重复的HTTP ://stackoverflow.com/questions/4073752/renaming-an-uploaded-file-in-codeigniter) –

回答

56

您可以使用CI本地选项的加密文件名:

$config['encrypt_name'] = TRUE; 

OR

你可以用自己的代码做到这一点:

$new_name = time().$_FILES["userfiles"]['name']; 
$config['file_name'] = $new_name; 
7

对于有些原因,连续调用do_upload函数不起作用。它坚持由第一个函数调用

$small_photo_url = $this->upload_photo('picture_small', $this->next_id.'_small '); 
$medium_photo_url = $this->upload_photo('picture_medium', $this->next_id.'_medium'); 
$large_photo_url = $this->upload_photo('picture_large', $this->next_id.'_large '); 

的文件名设置的第一个文件名都将给出如下配置

function upload_photo($field_name, $filename) 
{ 
    $config['upload_path'] = 'Public/uploads/'; 
    $config['allowed_types'] = 'gif|jpg|png'; 
    $config['max_size'] = '1024'; 
    $config['max_width'] = '1024'; 
    $config['max_height'] = '768'; 
    $config['file_name'] = $filename; 

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

    if (! $this->upload->do_upload())... 

我认为这是“00001_small”,“00001_small1”,“00001_small2” 因为这条线在您第二次打电话时不起作用。它不会再次设置配置

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

==================================== ====================================== 解决连续do_upload函数调用期间遇到的问题:

// re-initialize upload library 
$this->upload->initialize($config); 
+0

我有完全相同的问题......你遇到过任何解决方案? –

+0

找到解决这个问题的办法。如果有人在寻找解决方案,我会把这里放在这里。解决方法很简单... 负荷在构造函数库 '$这个 - >负载>库(“上传”);' 然后上传之前每次初始化函数, '$这个 - > upload- >初始化($ config);' 它会工作... –

0
$config['file_name'] = $new_name; 

只需添加它的配置代码一致。

-2

这应该是在上传之后。

过程中的文件名,你想在这里:

$a=$this->upload->data();   
rename($a['full_path'],$a['file_path'].'file_name_you_want'); 
2

为了什么你究竟在寻找,这个工作对我来说:

$path = $_FILES['image']['name']; 
$newName = "<Whatever name>".".".pathinfo($path, PATHINFO_EXTENSION);