简体   繁体   English

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

[英]unable to upload file in codeigniter using AJAX

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. 我正在尝试使用Ajax在CodeIgniter中上载文件,但是问题是文件正在数据库中上载,但是在不加载页面的情况下无法执行。 Every time I upload a file it uploading successfully but navigating to its controller address with JSON code. 每次我上传文件时,它都会成功上传,但是会使用JSON代码导航到其控制器地址。 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 Ajax代码

<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. 当前,它正在上传文件,但是在将其导航到控制器地址之后。

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 . 导航到控制器的原因是因为对preventDefault是从不存在的标识符e引起的,所以可以将其删除,因为稍后您返回false或仅定义e
Now when you're trying to upload a file with ajax you use a FormData object 现在,当您尝试使用ajax上传文件时,可以使用FormData对象

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

Slightly different variation of solution that worked for me is given below: 下面给出了对我有用的解决方案略有不同的变化:

<script type="text/javascript">
    $(function() {

        $('#upload_file').unbind('submit').bind('submit', function(e) {
            e.preventDefault();
            var file = document.getElementById('userfile').files[0];
            if(file==undefined){
                return false;
            }
            var formData = false;
            if (window.FormData) {
                formData = new FormData();
                formData.append("userfile", file);
            }
            var form = $(this);
            if(formData!==false){
                $.ajax({
                    url : form.attr('action'),
                    type: form.attr('method'),
                    data: formData,
                    processData: false,
                    secureuri: false,
                    contentType: false,
                    success : function (data, status)
                    {
                        if(data.status != 'error')
                        {
                            $('#files').html('<p>Reloading files...</p>');

                        }
                        alert(data.msg);
                    }
                });
            }
            return false;
        });
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM