2016-03-24 4 views
2

Я пытаюсь использовать две кнопки закачивать файл в CodeIgniter, как показано нижеИспользуйте два файла Кнопка загрузки в CodeIgniter

<label class="control-label" for="default">PO File</label> 
<input type="file" id="po_file" name="po_file" multiple="multiple" > 
<label class="control-label" for="default">Invoice File</label> 
<input type="file" id="in_file" name="in_file" multiple="multiple" > 

в контроллере

$file1 = $_FILES['po_file']['name']; 
    $file2 = $_FILES['in_file']['name']; 
    $config['upload_path'] = $pathToUpload; 
    $config['allowed_types'] = 'pdf'; 
    $config['overwrite' ] =TRUE; 
    $config['max_size'] =0; 


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

    if (! $this->upload->do_upload()) 
    { 
     echo $this->upload->display_errors(); 

     // $this->load->view('file_view', $error); 
    } 
    else 
    { 

     $this->upload->do_upload(file1); 
     $upload_data = $this->upload->data(); 
     $file_name = $upload_data['file_name']; 
    } 

Я попытался, как это, но он дал Вы сделали не выберите файл для загрузки. Любая помощь, как это сделать ??? спасибо

ответ

0

первый в вашем php.ini file_uploads = О

Второму быть уверены, что

<form action="controller/action" method="post" enctype="multipart/form-data"> 

третьей проверки, что на CodeIgniter documentaion о загружаемом файле. https://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

не забудьте расширение файлов allowd

+0

Я смог загрузить файл, когда я использовал userfile как имя текстового поля , но я хочу переименовать его на свое имя – sasy

0

Если вы видите upload.php файл библиотеки в папке системы, то вы будете знать, что CI принимает «UserFile» имя поля по умолчанию, поэтому, когда вы делаете

if (! $this->upload->do_upload()) 
{ 
    echo $this->upload->display_errors(); 

    // $this->load->view('file_view', $error); 
} 

//Passing parameter empty, then CI search for 'userfile'. 

Попробуйте передавая имя поля, как вы сделали в другом состоянии, или установить один из имени входного поля к «UserFile».

3

Видя вашу форму в вопросе, я предполагаю, что вы хотите загрузить два файла из двух разных полей ввода. Это оно ?

Таким образом, делая это на вашем пути, ваша форма должна быть:

<form enctype="multipart/form-data" method="post"> <!-- enctype="multipart/form-data" is must, method 'post' or 'get' is depend on your requirement --> 

    <?php 
     if(!empty($notification)) 
     { 
      echo ' 
      <p>Notifications : </p> 
      <p>'.$notification.'</p>'; <!-- For the status of the uploaded files (error or success) --> 
     } 
    ?> 

    <label for="default">PO File</label> 
    <input type="file" name="po_file"> <!-- no need to add "multiple" attribute, unless you want multiple files to be uploaded in the same input field--> 
    <label for="default">Invoice File</label> 
    <input type="file" name="in_file"> 

    <input type="submit" name="upload"> 

</form> 

И ваш контроллер должен быть как:

class Image extends CI_Controller { 

    private $data; // variable to be used to pass status of the uploaded files (error or success) 

    function __construct() 
    { 
     // some code 
    } 

    public function upload() 
    { 
     $this->data['notification'] = ''; 

     if($this->input->post('upload')) // if form is posted 
     { 
      // setting the config array 

      $config['upload_path']  = 'uploads/'; // $pathToUpload (in your case) 
      $config['allowed_types'] = 'pdf'; 
      $config['max_size']   = 0; 

      $this->load->library('upload', $config); // loading the upload class with the config array 

      // uploading the files 

      $this->lets_upload('po_file'); // this function passes the input field name from the form as an argument 

      $this->lets_upload('in_file'); // same as above, function is defined below 
     } 

     $this->load->view('form', $this->data); // loading the form view along with the member variable 'data' as argument 
    } 

    public function lets_upload($field_name) // this function does the uploads 
    { 
     if (! $this->upload->do_upload($field_name)) // ** do_upload() is a member function of upload class, and it is responsible for the uploading files with the given configuration in the config array 
     { 
      $this->data['notification'] .= $this->upload->display_errors(); // now if there's is some error in uploading files, then errors are stored in the member variable 'data' 
     } 
     else 
     { 
      $upload_data = $this->upload->data(); // if succesful, then infomation about the uploaded file is stored in the $upload_data variable 

      $this->data['notification'] .= $upload_data['file_name']." is successfully uploaded.<br>"; // name of uploaded file is stored in the member variable 'data' 
     } 
    } 
} 

Теперь предположим, вы хотите новый файл изображения будет загружается в другом месте или что-то еще, из той же формы; то в массиве конфигурации, вы должны изменить только элементы массива, которые вы хотите быть различными:

$config['upload_path'] = '/gallery'; 
$config['allowed_types'] = 'gif|jpg|jpeg|png'; 

Затем вы должны инициализировать массив конфигурации, как:

$this->upload->initialize($config); // *** this is important *** 

, а затем у вас есть загрузить класс загрузки с этой новой конфигурации, как:

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

и теперь вы можете вызвать функцию lets_upload():

$this->lets_upload('img_file'); 

в функции upload().