【问题标题】:How to upload image using ajax and codeigniter without resetting the form?如何在不重置表单的情况下使用 ajax 和 codeigniter 上传图像?
【发布时间】:2019-02-13 07:39:50
【问题描述】:

我只是想使用 ajax 和 codeigniter 上传图像。收到错误提示“您没有选择要上传的文件”。即使我确实选择了那张图片。

我最近尝试了许多来源的许多示例,但没有得到我的答案。在我向您展示我的代码之后,这给了我“您没有选择要上传的文件”的结果。当我已经选择了文件时。

这是我的看法:

<div class="col-lg-6">
   <div class="dropify-wrapper mb-4 form-group col-lg-6">
       <div class="dropify-loader"></div>
        <div class="dropify-errors-container">
        <ul></ul>
        </div>
        <input class="dropify" name="userfile" id="input-file-now" type="file">
        <button class="dropify-clear" type="button">Remove</button>
        <div class="dropify-preview">
        <span class="dropify-render"></span>
        <div class="dropify-infos">
        <div class="dropify-infos-inner">
        <p class="dropify-filename"><span class="file-icon"></span>
        <span class="dropify-filename-inner"></span></p>
        <p class="dropify-infos-message">Drag and drop or click to replace</p>
        </div>
        </div>
        </div>
      </div>
    </div>

这是 ajax 代码:

$('#submit_btn').click(function (e) {
   e.preventDefault();
   var data = $('#formname').serialize();

   $.ajax({
      type: 'ajax',
      method: 'post',
      url: '<?php echo base_url() ?>ControllerName/functionName',
      data: data,
      enctype: 'multipart/form-data',
      async: false,
      dataType: 'json',

      success: function (response) {
         alert(response);
      },

      error: function () {

      }
   });
});

这是控制器代码:

public function functionName()
{
    $config=[
      'upload_path'=>'./Assets/imgs/users/',
      'allowed_types'=>'jpg|png|gif' 
    ];       
    $this->load->library('upload',$config);
    if($this->upload->do_upload(')){
        $data=$this->upload->data();
        $image_path= base_url("Assets/imgs/users/".$data['raw_name'].$data['file_ext']);
        $result= $image_path;
    }else{
        $result=$this->upload->display_errors('','');
    }
}

【问题讨论】:

  • 你可以使用dropzone js
  • 当我提交没有 ajax 的表单时,文件正在上传,但使用 ajax 时,文件没有上传

标签: php jquery ajax codeigniter


【解决方案1】:

请在您的 html 中添加标签,并在 jquery 代码中使用 formdata,如下所示。

HTML 代码:

<form id="form" method="post" enctype="multipart/form-data">
</form>

jQuery 代码:

  data:  new FormData(formid),   

【讨论】:

  • 是的,我有像
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-26
  • 2014-12-13
  • 2020-10-29
  • 2013-05-09
  • 2011-02-02
  • 1970-01-01
  • 2014-10-04
相关资源
最近更新 更多