【问题标题】:unable to upload file in codeigniter using AJAX无法使用 AJAX 在 codeigniter 中上传文件
【发布时间】:2018-07-23 15:23:37
【问题描述】:

我正在尝试使用 Ajax 在 CodeIgniter 中上传文件,但问题是文件正在上传到数据库中,但如果不加载页面就无法完成。每次我上传文件时,它都会成功上传,但会使用 JSON 代码导航到其控制器地址。我只想上传文件而不刷新页面。

查看文件

<?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 代码

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

控制器

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

我只想上传文件而不刷新页面。目前,它正在上传文件,但上传后导航到控制器地址。

【问题讨论】:

    标签: php jquery ajax codeigniter


    【解决方案1】:

    您导航到控制器的原因是因为您对 preventDefault 的调用来自不存在的标识符 e 导致错误,您可以将其删除,因为您稍后返回 false 或仅定义 e .
    现在,当您尝试使用 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;
      });
    });
    

    【讨论】:

    • 非常感谢,我刚刚明白了
    【解决方案2】:

    下面给出了对我有用的稍微不同的解决方案:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 2012-07-18
      • 2020-06-26
      • 1970-01-01
      • 2020-02-05
      • 2017-01-26
      • 1970-01-01
      相关资源
      最近更新 更多