dtnnpt11795 2018-07-23 15:23
浏览 77
已采纳

无法使用AJAX在codeigniter中上传文件

I'm trying to upload the file in CodeIgniter using Ajax but the problem is the file is uploading in the database but unable to do it without loading the page. Every time I upload a file it uploading successfully but navigating to its controller address with JSON code. I just want to upload the file without refreshing page.

View FILE

<?php echo form_open_multipart('maker/Checkout/docs', array('id'=>'upload_file')); ?>


          <div class="form-group">
              <label for="userfile">Upload existing CV</label>
              <input class="form-control" type="file" name="userfile" id="userfile" size="20" />
          </div>

          <div class="form-group">
            <button class="btn btn-info" type="submit">Upload</button>
          </div> 

       <?php echo form_close() ?> 

Ajax Code

<script>

  $(function() {
    $('#upload_file').unbind('submit').bind('submit', function() {
      e.preventDefault();
       var form = $(this);
         $.ajax({
          url : form.attr('action'), 
          type: form.attr('method'),
          data: form.serialize(),
          secureuri   :false,
          fileElementId :'userfile',
          dataType    : 'json',
          success : function (data, status)
          {
            if(data.status != 'error')
            {
              $('#files').html('<p>Reloading files...</p>');

            }
            alert(data.msg);
          }
        });
        return false;
      });
  });

</script>

Controller

public function docs() {
      $status = "";
      $msg = "";
      $file_element_name = 'userfile';


    if ($status != "error")
    {
        $config['upload_path'] = dirname($_SERVER["SCRIPT_FILENAME"])."/assets/img/posts";
        $config['upload_url']  = base_url()."/assets/img/posts";
        $config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|docx|docs|txt|xml';
        $config['max_height'] = 102048;
        $config['max_width']  = 102048;
        $config['max_size'] = 1024 * 8;
        $config['encrypt_name'] = TRUE;

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

        if (!$this->upload->do_upload($file_element_name))
        {
            $status = 'error';
            $msg = $this->upload->display_errors('', '');
        }
        else
        {
            $data = $this->upload->data();
            $file_id = $this->Checkout_model->newcheckout($data['file_name']);
            if($file_id)
            {
                $status = "success";
                $msg = "File successfully uploaded";
            }
            else
            {
                unlink($data['full_path']);
                $status = "error";
                $msg = "Something went wrong when saving the file, please try again.";
            }
        }
        @unlink($_FILES[$file_element_name]);
      }
      echo json_encode(array('status' => $status, 'msg' => $msg));
    }

I just want to upload the file without refreshing the page. Currently, it's uploading the file but after upload its navigating to the controller address.

  • 写回答

2条回答 默认 最新

  • dsyq40772 2018-07-23 15:35
    关注

    The reason why you're navigating to controller is because your call to preventDefault is from a non existent identifier e causing an error, you can remove it since you have return false later or just define the e.
    Now when you're trying to upload a file with ajax you use a FormData object

    $(function() {
      $('#upload_file').unbind('submit').bind('submit', function(e) {//<-- e defined here
        e.preventDefault();
        var form = $(this);
        var data = new FormData(this);
        $.ajax({
          url : form.attr('action'), 
          type: form.attr('method'),
          data: data,
          processData: false,
          contentType: false, 
          dataType    : 'json',
          success : function (data, status)
          {
            if(data.status != 'error')
            {
              $('#files').html('<p>Reloading files...</p>');
    
            }
            alert(data.msg);
          }
        });
        return false;
      });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了