如何使用CodeIgniter上传文件数组?我有一个表单,我希望用户能够一次上传多个文件。我有一个javascript代码,当他们点击提交按钮时,会添加一个名为“files []”的额外文件输入字段。这是我到目前为止的代码,但它总是说我没有在display_errors函数中选择要上传的文件。
<code>
foreach($this->input->post('files') as $i => $file){
$config = array( //Preferences to validate the image before uploading it
'upload_path' => './attachments',
'allowed_types' => 'jpg|gif|bmp',
'max_size' => '100',
'max_width' => '950',
'max_height' => '631',
'overwrite' => FALSE,
'encrypt_name' => TRUE,
'remove_spaces' => TRUE
);
$this->load->library('upload', $config);
if($this->upload->do_upload('files['.$i.']')){
echo $this->upload->file_data();
} else {
echo $this->upload->display_errors('<li>', '</li>');
}
}
</code>
答案 0 :(得分:2)
你可以这样做。
在您看来:
<?php echo form_label('Image: ','userfile1');?>
<?php echo form_upload('userfile1');?>
<?php echo form_label('Image: ','userfile2');?>
<?php echo form_upload('userfile2');?>
<!-- and so on -->
然后在你的控制器中,像这样......
//Set File Settings
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'jpg|png';
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
// Validate files for upload section...
$success = array();
$errors = array();
$updload_files = array(
'userfile1' => $_FILES['userfile1'],
'userfile2' => $_FILES['userfile2'],
// You can add more
);
foreach($updload_files as $field => $updload_file)
{
// Only process submitted file
if($updload_file['error'] == 0)
{
// If there is an error, save it to error var
if( ! $this->upload->do_upload($field) )
{
$errors[] = 'Failed to upload '.$field;
}
// Use this to get the new file info if you need to insert it in a database
$success[] = array( 'Success to upload '.$field => $this->upload->data());
}
else
{
$errors[] = $field . ' contain no data';
}
}
// Heres you could gettin know whats happen
var_dump($errors);
var_dump($success);
答案 1 :(得分:0)
请使用
if( $this->upload->do_upload($files) ) {
而不是
if($this->upload->do_upload('files['.$i.']')) {
如果您使用的是第二行,则上传的文件包含文件[0],文件[1],...名称
由于您已经拥有存储在$ file变量中的当前循环的值,您可以直接使用它。