如何从Codeigniter上传控制器获取图像名称?

时间:2013-03-16 20:47:25

标签: php codeigniter file-upload

例如,如果我上传文件foo.png,我怎样才能在上传控制器中获得字符串“foo.png”?

控制器代码为:

<?php

class Upload extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
        $this->load->database();
    }

    function do_upload($folder)
    {
        $config['upload_path'] = './userdata/'. $folder . '/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '100';
        $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());
            echo $this->upload->display_errors();
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());
            echo "<p>File sucesfully uploaded</p>";

            $filename = // How do I get the filename here

        }
    }
}
?>

如何将$filename设置为上传文件的文件名?

3 个答案:

答案 0 :(得分:4)

来自official CI manual

$this->upload->data()
This is a helper function that returns an array containing all of the data related to the file you uploaded. Here is the array prototype:
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"
)

因此,在您的情况下,保存$data函数结果的$this->upload->data()变量应包含您上传文件所需的所有信息。

具体而言,$data['upload_data']['file_name']正是您所寻找的。

答案 1 :(得分:2)

试试这个!

$data = $this->upload->data();
echo $data['file_name'];

答案 2 :(得分:1)

echo $data['raw_name'].$data['file_ext'];

应该做的伎俩

e.g。你上传你的图像

if($this->upload->do_upload('upload_data')) {
$data = $this->upload->data();
echo $data['raw_name'].$data['file_ext'];
}