1

我有两个字段可以上传两个扩展:

  • 要上传的第一个字段(PDF、doc、docx)

  • 第二个要上传的字段(zip)

如何让 Codeigniter 验证不同字段的不同扩展?

/**
 * change book source file
 * 
 * @param integer $book_id 
 */
public function upload_book_source($book_id) {
    $vars = array();
    $vars['upload_path'] = PUBPATH . 'global/modules/bookstore/files/books_source_file/';
    $vars['allowed_types'] = 'doc|docx|pdf|zip';
    $vars['max_size'] = '30720';
    $vars['encrypt_name'] = TRUE;
    $vars['book_id'] = $book_id;

    $book = $this->d_book->find_by_id($book_id);
    if (isset($_POST['submit'])) {
        $file_name = $this->upload($vars);
        $this->d_book->update_one_field($book_id, 'bo_path', $file_name[0]['file_name']);
        $this->d_book->update_one_field($book_id, 'bo_path_zip', $file_name[1]['file_name']);

        $this->session->set_flashdata('success_msg', lang('file_uploaded'));
        redirect('bookstore/admin_d_book/');
    } else {
        $vars['upload_errors'] = NULL;
    }

    if ($book->bo_path) { // load cover image
        $vars['file_path'] = base_url() . 'global/modules/bookstore/files/books_source_file/' . $book->bo_path;
    } else {
        $vars['file_path'] = NULL;
    }
    $vars['controller_name'] = 'admin_d_book';
    $this->view('bookstore/admin/change_source_file', $vars);
}

/**
 * 
 * @param array $config the configuration array
 * @return string
 * 
 */
private function upload($config) {
    $this->load->library('upload', $config);
    for ($i = 1; $i <= 2; $i++) {

        if (!empty($_FILES['file' . $i]['name'])) {

            if (!$this->upload->do_upload('file' . $i))
                $vars['upload_errors'] = $this->upload->display_errors("<p class='notification n-error'>", "</p>");
            else
                $result[] = $this->upload->data();
        }
    }
    return $result;
}
4

1 回答 1

1

您需要不同的配置,以便您可以更改allowed_types不同输入的配置,例如:

echo form_open_multipart();
echo form_upload('mydoc'); // <input type="file" name="mydoc">
echo form_upload('myzip'); // <input type="file" name="myzip">
echo form_close();
$config = array(
    // your default config
);
$this->load->library('upload', $config);

$config['allowed_types'] = 'doc|docx|pdf';
$this->upload->initialize($config);
$this->upload->do_upload('mydoc');

$config['allowed_types'] = 'zip';
$this->upload->initialize($config);
$this->upload->do_upload('myzip');
于 2012-12-03T15:47:22.763 回答