简体   繁体   中英

Codeigniter Rename file on upload

I'm trying to add time as the prefix of the image name along with the original name when uploading, But I couldn't figure it out. Please help me with the following code to add a prefix to my original file name when uploading.

<?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);
        }
    }
}
?>

You can encrypt file name with use of CI native option:

$config['encrypt_name'] = TRUE;

OR

You can do it with your own code:

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

For some reasons, consecutive calls to the do_upload function doesn't work. It sticks to the first filename set by the first function call

$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 ');

The filenames will all be "00001_small", "00001_small1", "00001_small2" given the following configurations

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())...

I think it's because this line doesn't work the second time you call it. It does not set the configurations again

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

========================================================================== Solution to the problem faced during consecutive do_upload function calls:

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

For what you are exactly looking for, this worked for me:

$path = $_FILES['image']['name'];
$newName = "<Whatever name>".".".pathinfo($path, PATHINFO_EXTENSION); 
        /* Conf */
        $new_name                   = time().$_FILES["userfiles"]['name'];
        $config['file_name']        = $new_name;
        $config['upload_path']      = './upload/';
        $config['allowed_types']    = 'gif|jpg|png';
        $config['max_size']         = '';
        $config['max_width']        = '';
        $config['max_height']       = '';
        $config['file_ext_tolower'] = TRUE;

      /*  Load the upload library  */   
        $this->load->library('upload', $config);

when you use do_upload() function its rename file name if already exists and upload file

System->libraries->Upload.php

default function of do_upload() return true or false replace

return $this->upload_path.$this->file_name;

and in another file

 <input type='file' name='userfile'/>


<?php
    $upload_file_name = $this->upload->do_upload('userfile');
                $finalname;
                if (!$upload_file_name) {
                    $finalname = 'default.png';
                } else {

                    $split_data_upload_file_name = explode("/", $upload_file_name);
                    foreach ($split_data_upload_file_name as $i => $value) {

                        $finalname = $value;
                    }
                }

?>
$config['file_name'] = $new_name;

只需添加它与配置代码对齐。

This should be after the upload.

Process the filename you want here:

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

尝试这个:

$config['file_name'] = "yourCustomFileName";

If your $config is with this code: $config['encrypt_name'] = TRUE; the name of your file will be forced to rename with a encrypt name, just remove the code.

Solution 1: Upload file with new customized and specific name (Note: this answer is applicable when you are submitting a unique name of a record, for example student name is a unique value in a record then you will use $_POST['student_name'] )

$config['file_name'] = str_replace(' ', '_', $_POST['anyUniqueValue']);
//any Other unique value that you are using to submit with this file
$config['upload_path'] = './folderName/';
$config['encrypt_name'] = FALSE;

Solution 2: Upload file with new unique name

$config['file_name'] = time();
$config['upload_path'] = './folderName/';
$config['encrypt_name'] = FALSE;

Solution 3: Upload file with new unique name using codeigniter's default option

$config['encrypt_name'] = TRUE;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM