Codeigniter在上传时重命名文件

Dil*_*dra 33 php codeigniter file-upload

我正在尝试在上传时添加时间作为图像名称的前缀以及原始名称,但我无法弄明白.请帮我使用以下代码在上传时为我的原始文件名添加前缀.

<?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);
        }
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

Kum*_*r V 87

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

$config['encrypt_name'] = TRUE;
Run Code Online (Sandbox Code Playgroud)

要么

您可以使用自己的代码执行此操作:

$new_name = time().$_FILES["userfiles"]['name'];
$config['file_name'] = $new_name;
Run Code Online (Sandbox Code Playgroud)


Car*_*ela 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 ');
Run Code Online (Sandbox Code Playgroud)

给定以下配置,文件名均为"00001_small","00001_small1","00001_small2"

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())...
Run Code Online (Sandbox Code Playgroud)

我认为这是因为第二次调用它时这行不起作用.它不会再次设置配置

$this->load->library('upload', $config);
Run Code Online (Sandbox Code Playgroud)

================================================== ========================连续do_upload函数调用中遇到的问题的解决方案:

// re-initialize upload library
$this->upload->initialize($config);
Run Code Online (Sandbox Code Playgroud)

  • 找到了这个问题的解决方案。如果有人在寻找解决方案,我会放在这里以防万一。解决方法很简单...在构造函数中加载库`$this-&gt;load-&gt;library('upload');`然后每次上传前都初始化函数,`$this-&gt;upload-&gt;initialize($config) ;`它会工作... (2认同)