【问题标题】:Codeigniter - Upload multiple files and displaying filesCodeigniter - 上传多个文件并显示文件
【发布时间】:2020-08-30 08:49:39
【问题描述】:

我的网络应用只允许上传一个文件,这是一个问题,因为用户希望能够在必要时提交 2 个或更多文件。 请问如何允许多个文件上传并显示这些文件由其他类型的用户下载?

型号

  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);
   }

    }

控制器

 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;
          }

        }


    }

查看

 <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>

这样显示的

控制器

 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);
    }

查看

 <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>

感谢所有帮助我的人。我按照你们的指示做了。但是,我注意到我现在可以选择多个文件,但卡在保存按钮上。 当我点击时,什么也没有发生。未提交数据。 这就是我到目前为止所做的

控制器

  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);
    }
    }
    }

查看

 <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>

【问题讨论】:

  • 我懒得修复您的代码,但会提供线索。对于 ,添加 ''multiple'' 属性。然后,从您的后端,您需要循环它。通常它会在数组中。此外,您可能想了解如何清理文件上传。

标签: php codeigniter file-upload


【解决方案1】:

HTML

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

将名称设置为 file[] 将接受文件数组

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
       }
   }
}

希望这有帮助:)

【讨论】:

    【解决方案2】:

    如果有帮助,请提供一些提示。不要忘记投票加强。走吧……

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

    在你的控制器上很简单......

    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);
      }
    }
    

    要显示多个文件,您需要使用与上传相同的概念

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

    我希望我有所帮助。成功!

    【讨论】:

      【解决方案3】:

      设置属性multiple 将允许通过按ctrl 一次选择多个文件,将名称设置为数组(file[]) 将允许存储多个文件名。

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

      但是,如果您不希望用户一次上传多个文件,那么您必须创建多个与数组同名的 input 字段(file[])

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

      在您的控制器中,您必须遍历每个元素,因为它现在是一个数组。

      foreach($_FILES["file"]['name'] as $file){ //single element 
      
          echo $file; // returns the name of file
          // your-logic-to-upload
      
      }
      

      如果您在上传多个文件时遇到问题,请参阅 hereherehere。 希望它可以帮助你。

      【讨论】:

      • 你好,我修改了我的帖子。请看看我做了什么。我现在可以选择多个文件,但是当我点击保存按钮时,什么也没有发生
      • 将您的action 更改为echo base_url()."your-controller/upload_docs",如果您在上传文件时遇到问题,请参考我提供的3 链接,它们可以帮助您完成上传过程
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 2012-03-05
      • 2013-07-31
      • 1970-01-01
      相关资源
      最近更新 更多