CodeIgniter - 从单个表单上传多个文本条目和文件

时间:2012-08-28 22:23:42

标签: codeigniter

我在页面上有一个表单。它有5个文本字段和3个上传文件字段。我需要将文本和文件路径写入数据库。我在网上看过很多例子,但大多数是上传单个文件或从同一个上传字段上传多个文件。

我是CodeIgniter的新手,所以代码片段会非常有用。

非常感谢提前。

2 个答案:

答案 0 :(得分:1)

HOpe这有帮助

$config['upload_path'] = $path; //$path=any path you want to save the file to...
$config['allowed_types'] = 'gif|jpg|png|jpeg'; //this is the file types allowed
$config['max_size'] = '1024'; //max file size

$config['max_width']  = '1024';//if file type is image
$config['max_height']  = '768';//if file type is image
//etc config for file properties, you can check all of them out on website

现在假设你有3个文件,你要保存为 1.jpg,2.jpg,3.gif ,它们通过3个输入字段上传, pic1,pic2, pic3 这是你做的事情

for($ite=1;$ite<=3;$ite++){
    if(!empty($_FILES["pic".$ite]["name"])){ //if file is present
        $ext = pathinfo($_FILES['pic'.$ite]['name'], PATHINFO_EXTENSION); //get extension of file
        $config["file_name"]="$ite.$ext"; //rename file to 1.jpg,2.jpg or 3.jpg, depending on file number and its extension

        $this->upload->initialize($config); //upload library of codeigniter initialize function with config properties set earlier
        if(!$this->upload->do_upload("pic".$ite)){
            //error code

        }

        }
    }

答案 1 :(得分:1)

另一个建议是:

function upload()
{
    $config['upload_path'] = $path; //$path=any path you want to save the file to...
    $config['allowed_types'] = 'gif|jpg|png|jpeg'; //this is the file types allowed
    $config['max_size'] = '1024'; //max file size

    $config['max_width']  = '1024';//if file type is image
    $config['max_height']  = '768';//if file type is image

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

    foreach($_FILES as $Key => $File)
    {
        if($File['size'] > 0)
        {
            if($this->upload->do_upload($Key))
            {
                $data = $this->upload->data();
                echo $data['file_name'];
            }
            else
            {
                // throw error
                echo $this->upload->display_errors();
            }
        }
    }
}

这将自动适用于您发布的所有文件输入,并且不关心名称或数量:)