使用Ajax在codeigniter中上传文件

时间:2014-08-25 12:19:25

标签: php jquery ajax codeigniter

嗯......我是codeigniter的新手。而且我几天都坚持这个问题! 我阅读了很多关于使用ajax上传文件的问题和答案。但我无法找到解决问题的具体方法。 有观点:

<?php echo form_open_multipart('upload/upload_cover', array("id" => "upload_file"));?>
<input type="file" id="coverpic" name="userfile" size="20" class="btn btn-primary" style="float: right"/>
<br /><br />
<input type="submit" name="submit" id="submit" class="btn btn-primary" style="float: right" value="Upload">
</form>

控制器:上传,方法upload_cover

public function upload_cover() {
$file = $_FILES['userfile']['tmp_name'];
$userid = $this->session->userdata('userid');
$ext = end(explode('.', $_FILES['userfile']['name']));
$_FILES['userfile']['name'] = "$userid.$ext";
$config['upload_path'] = './img/cover/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200000';
$config['max_width']  = '1024';
$config['max_height']  = '768';

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

  if ( !$this->upload->do_upload())
  {
    $error = array('error' => $this->upload->display_errors());
    $data['body'] = 'body_profile';
    $data['error'] = $error;
    $this->load->view('include/template_profile', $data);
  }
  else {
    $cover = "$userid.$ext";
    echo $cover;
    $this->load->model('dbconnect');
    $this->dbconnect->editCover($userid, $cover);
    //$this->index();
    $data = $this->upload->data();
    $image_path = $data['full_path'];
    if(file_exists($image_path))
    {
      echo json_encode($image_path);
    }
    //redirect('homepage/');
    //echo base_url()."img/cover/".
  }

现在我的问题是......这段代码在没有ajax的情况下工作......我想用Ajax编写它,以便上传图片并在点击上传按钮时显示在div中。

那么我应该传递ajax请求的数据以使用上述控制器方法本身? 谢谢..

2 个答案:

答案 0 :(得分:0)

嗯..你需要jquery.form这样:

 $(document).ready(function() {
    var $form = $('#myform');
    var $btn = $('#submit'); // upload button

    $btn.click(function() {
        // implement with ajaxForm Plugin
        $form.ajaxForm({
            beforeSend: function() {
                // xyz
            },
            success: function(img_url) {
                $form.resetForm();
                alert(img_url);
                //$myimage.attr('src', img_url);
            },
            error: function(error_msg) {
                  alert('error:' + error_msg);
            }
        });
    });
});

你还需要从php返回(或存储在json中)一个url:)

答案 1 :(得分:0)

查看:

<div class="upload" id="upload" style="display:none">
    <form id="form-id" action="#" enctype="multipart/form-data" method="POST">
    <input type="file" id="coverpic" name="userfile" size="20" class="btn btn-primary" style="float: right"/>
    <br /><br />
    <input type="submit" name="submit" id="submit" class="btn btn-primary" style="float: right" value="Upload" />
    </form>
    </div>

控制器:上传,方法upload_cover

public function upload_cover() {
$userid = $this->session->userdata('userid');
$config['upload_path'] = 'C:\wamp\www\Twitter_Project\img\cover';
$config['upload_url'] = base_url().'files/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000KB';
$config['max_width'] = '4096';
$config['max_height'] = '2160';
$config['overwrite'] = TRUE;
$config['file_name'] = $userid;
$this->load->library('upload', $config);

  if (!$this->upload->do_upload())
  {
      //$error = array('error' => $this->upload->display_errors());

      //$this->load->view('upload_form', $error);
      echo "error";
  }
  else
  {
    //$username = $this->session->userdata('username');
    $ext = end(explode('.', $_FILES['userfile']['name']));
    $data = "$userid.$ext";
    //$data = array('upload_data' => $this->upload->data());
    $this->load->model('dbconnect');
    $this->dbconnect->editCover($userid, $data);

      //$this->load->view('upload_success', $data);
      echo json_encode($data);
  }
  @unlink($_FILES['userfile']);
  echo 'unlinked user file';
}

Ajax方法:

$('#form-id').on('submit', function(event){
event.preventDefault();
var data = new FormData($(this)[0]);
$.ajax({
url: base + 'upload/upload_cover',
type: 'POST',
dataType: 'json',
data: data,
processData: false,
contentType: false,
cache: false
}).done(function(data) {
  if(data !== 'error'){
    console.log("success");
    console.log(data);
    var path = base + 'img/cover/' + data;
    console.log(path);
    console.log( $('#sp1')[0].src);
    //$('#sp1')[0].src = path;
    $('#sp1').attr('src',path);
  }
  else{
    alert("Cannot upload your cover picture. Please try again.");
  }
})
});

这是一个有效的解决方案,必须单独编写模型方法。 现在,我不想让以前保存的图像名称取消链接,所以我在这里覆盖图像。除了更改文件名之外,有没有办法覆盖缓存的图像?