2014-02-16 120 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);