0

My web app only allows for one file upload which is an issue because users want to be able to submit 2 or more files when necessary. Please how do I allow multiple file uploads and displaying those files to be downloaded by another type of users?

MODEL

  public function upload_docs($data)
    {

   $this->db->where('homework_id',$data['homework_id']);
   $this->db->where('student_id',$data['student_id']);
   $q = $this->db->get('submit_assignment');

   if ( $q->num_rows() > 0 ) 
   {
      $this->db->where('homework_id',$data['homework_id']);
       $this->db->where('student_id',$data['student_id']);
      $this->db->update('submit_assignment',$data);
   } else {

      $this->db->insert('submit_assignment',$data);
   }

    }

CONTROLLER

 public function upload_docs()
    {

        $homework_id         = $_REQUEST['homework_id'];
        $student_id          =$_REQUEST['student_id'];
        $data['homework_id'] = $homework_id;
        $data['student_id']  = $student_id;
        $data['message']     = $_REQUEST['message'];
        // $data['id']=$_POST['assigment_id'];
         $is_required=$this->homework_model->check_assignment($homework_id,$student_id);
          $this->form_validation->set_rules('message', $this->lang->line('message'), 'trim|required|xss_clean');

  $this->form_validation->set_rules('file', $this->lang->line('attach_document'), 'trim|xss_clean|callback_handle_upload['.$is_required.']');

        if ($this->form_validation->run() == FALSE) {
          $msg=array(
            'message'=>form_error('message'),
            'file'=>form_error('file'),
          );
          $array = array('status' => 'fail', 'error' => $msg, 'message' => '');

        }else{

             if (isset($_FILES["file"]) && !empty($_FILES['file']['name'])) {
                $time     = md5($_FILES["file"]['name'] . microtime());
                $fileInfo = pathinfo($_FILES["file"]["name"]);
                $img_name = $time . '.' . $fileInfo['extension'];           
            $data['docs'] =  $img_name;
            move_uploaded_file($_FILES["file"]["tmp_name"], "./uploads/homework/assignment/" . $data['docs']);

            $data['file_name']=$_FILES["file"]['name'];

            $this->homework_model->upload_docs($data);
        }

         $array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('success_message'));
        }

        echo json_encode($array);
    }

    public function handle_upload($str,$is_required)
    {

        $image_validate = $this->config->item('file_validate');

        if (isset($_FILES["file"]) && !empty($_FILES['file']['name']) && $_FILES["file"]["size"] > 0) {

            $file_type         = $_FILES["file"]['type'];
            $file_size         = $_FILES["file"]["size"];
            $file_name         = $_FILES["file"]["name"];
            $allowed_extension = $image_validate['allowed_extension'];
            $ext               = pathinfo($file_name, PATHINFO_EXTENSION);



            $allowed_mime_type = $image_validate['allowed_mime_type'];

            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mtype = finfo_file($finfo, $_FILES['file']['tmp_name']);
            finfo_close($finfo);

            if (!in_array($mtype, $allowed_mime_type)) {
                $this->form_validation->set_message('handle_upload', 'File Type Not Allowed');
                return false;
            }

            if (!in_array($ext, $allowed_extension) || !in_array($file_type, $allowed_mime_type)) {
                $this->form_validation->set_message('handle_upload', 'Extension Not Allowed');
                return false;
            }

            if ($file_size > $image_validate['upload_size']) {
                $this->form_validation->set_message('handle_upload', $this->lang->line('file_size_shoud_be_less_than') . number_format($image_validate['upload_size'] / 1048576, 2) . " MB");
                return false;
            }

            return true;
        } else {
          if($is_required==0){
             $this->form_validation->set_message('handle_upload', 'Please choose a file to upload.');
            return false;
          }else{
             return true;
          }

        }


    }

VIEW

 <form id="upload" role="form" method="post" class="ptt10" enctype="multipart/form-data" action="upload_docs">
                <div class="modal-body pt0">
                            <div class="row">
                                <input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
                                <input type="hidden" id="homework_id"  name="homework_id">
                                <input type="hidden" id="assigment_id" name="assigment_id">
                                <div class="col-sm-12">
                                    <div class="form-group">
                                        <label for="pwd"><?php echo $this->lang->line('message'); ?></label>
                                        <textarea type="text" id="assigment_message" name="message" class="form-control "></textarea>
                                    </div> 
                                </div>
                                <div class="col-sm-12">
                                    <div class="form-group">
                                        <label for="pwd"><?php echo $this->lang->line('attach_document'); ?></label>
                                        <input type="file" id="file" name="file" class="form-control filestyle">
                                    </div>
                                </div>
                                <p id="uploaded_docs"></p>
                            </div>


                </div>
                <div class="box-footer">
                    <div class="" id="footer_area">
                        <button type="submit" form="upload" class="btn btn-info pull-right" id="submit" data-loading-text='Please wait...'><?php echo $this->lang->line('save'); ?></button>
</div>
                </div>
            </form>

This is displayed like this

controller

 public function assigmnetDownload($doc)
    {
        $this->load->helper('download');
        $name     = $this->uri->segment(5);
        $ext      = explode(".", $name);
        $filepath = "./uploads/homework/assignment/" . $doc;
        $data     = file_get_contents($filepath);
        force_download($name, $data);
    }

view

 <table class="table table-hover table-striped table-bordered example">
                                        <thead>
                                            <tr>
                                                <th><?php echo $this->lang->line('name') ?></th>
                                                <th><?php echo $this->lang->line('message') ?></th>

                                                <th class="text-right"><?php echo $this->lang->line('action') ?></th>
                                            </tr>

                                        </thead>
                                        <tbody id="homework_docs_result">
                                        </tbody>
                                    </table>

Thanks to all helping me out. I did as you guys directed. However, I noticed I'm able to select multiple files now but gets stuck on the save button. When I click, nothing happens. Data is not submitted. This is what I have done so far

controller

  if (isset($_FILES["file"])){
            foreach($_FILES["file"] as $file){ 
            if(!empty($file["name"])){
                $time     = md5($file["file"]['name'] . microtime());
                $fileInfo = pathinfo($file["file"]["name"]);
                $img_name = $time . '.' . $fileInfo['extension'];           
            $data['docs'] =  $img_name;
            move_uploaded_file($file["file"]["tmp_name"], "./uploads/homework/assignment/" . $data['docs']);

            $data['file_name']=$file["file"]['name'];

            $this->homework_model->upload_docs($data);
        }

         $array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('success_message'));
        }

        echo json_encode($array);
    }
    }
    }

view

 <form id="upload" role="form" method="post" class="ptt10" enctype="multipart/form-data" action="uploaded_docs">
<input type="file"  multiple=""  id="file" name="file[]" class="form-control filestyle">
<button type="submit" form="upload" class="btn btn-info pull-right" id="submit" data-loading-text=' Please wait'><?php echo $this->lang->line('save'); ?></button>
</form>
  • i lazy to fix your code, but will give a clue. for , add ''multiple'' attribute. then, from your backend, you need to loop it. usually it will be in array. also, you might want to look into how to sanitize file upload. –  May 14 '20 at 01:01
  • https://stackoverflow.com/a/20138535/11024771 – Muhammad Saquib Shaikh May 15 '20 at 02:21

3 Answers3

0

HTML

<input type="file" id="file" name="file[]" class="form-control filestyle">

Setting name to file[] will accept array of files

PHP

if (isset($_FILES["file"]){
   foreach($_FILES["file"] as $file){ //this loop will get one file from 'file[]' array at a time
       if(!empty($file["name"])){
            //your alreay written code
            //replace $_FILES["file"] with $file
       }
   }
}

Hope this helpful :)

Dum
  • 1,431
  • 2
  • 9
  • 23
0

Some tips, if help. Do not forget the vote to strengthen. Let's go...

<form method="post" action="upload_docs" enctype="multipart/form-data">
 <input name="filesToUpload[]" type="file" multiple="" />
</form>

On your controller it's simple ...

if(isset($_FILES['filesToUpload'])) {
  foreach ($_FILES['filesToUpload'] as $fileUp) {
    $time = md5($fileUp["file"]['name'].microtime());
    $fileInfo = pathinfo($fileUp["file"]["name"]);
    $img_name = "{$time}.{$fileInfo['extension']}";
    $data['docs'] = $img_name;
    move_uploaded_file($fileUp["file"]["tmp_name"], "./uploads/homework/assignment/{$data['docs']}");
    $data['file_name']=$fileUp["file"]['name'];
    $this->homework_model->upload_docs($data);
  }
}

To display multiple files you need to use the same concept as uploading working with

foreach($files as $file){ ... }

I hope I helped. Success!

0

Setting attribute multiple will allow selecting multiple files at once by pressing ctrl, setting the name as an array(file[]) will allow more than files name to be stored.

<input type="file" id="file" name="file[]" class="form-control filestyle" multiple>

However, if you don't want the user to upload multiple files at once then you'll have to make multiple input fields with the same name as an array(file[])

<input type="file" id="file" name="file[]" class="form-control filestyle">
<input type="file" id="file1" name="file[]" class="form-control filestyle">
...
...

In your controller, you'll have to traverse through each element as it is now an array.

foreach($_FILES["file"]['name'] as $file){ //single element 

    echo $file; // returns the name of file
    // your-logic-to-upload

}

If you're having trouble uploading multiple files, see here, here and here. Hope it helps you.

sauhardnc
  • 1,961
  • 2
  • 6
  • 16
  • Hello, I modified my post. Please see what i have done. I'm able to select multiple files now but when I click the save button, nothing happens – MaryUghojor May 14 '20 at 23:42
  • change your `action` to `echo base_url()."your-controller/upload_docs"`, if you're having trouble uploading files, refer to the `3` links I provided, they help you with the uploading process – sauhardnc May 15 '20 at 04:23