Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

javascript - Ajax upload not working codeigniter

I am using codeigniter 3.1 . I want to post upload data using ajax.

Ajax upload file not working. But when i post the simple form without ajax, it working fine.

I don't know why but no error in console.

HTML

  <?php echo form_open_multipart(site_url("upload/post"), ['id' => 'uploader']) ?>
    <input type="file" name="userfile" value="">
    <input type="submit" value="Submit" />
  <?php echo form_close() ?>

JAVASCRIPT

   $('#uploader').submit(function (event) {
            event.preventDefault();
            $.ajax({
                url: window.location.href + '/post',
                type: "POST",
                dataType: 'json',
                data: new FormData(this)
               });
      });

CONTROLLERS

 public function post() 
    {
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->library("upload");
        $file = $this->common->nohtml($this->input->post("userfile"));

        $this->upload->initialize(array( 
               "upload_path" => 'upload',
               "overwrite" => FALSE,
               "max_filename" => 300,
               "encrypt_name" => TRUE
            ));

        $this->upload->do_upload('userfile');

        $data = $this->upload->data();

        $image_file = $data['file_name'];

  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Another approach to this would be passing to PHP the file encoded in base64:

  • get the selected file from #userfile field using $('#userfile').prop('files')[0];
  • transform the contents of that file into a base64 encoded string using FileReader.readAsDataURL(). We're going to call this content; Here's a similar question showing how to do and expanding the answer & possibilities;
  • send the AJAX passing both the filename and content strings;
  • now on CI, fetch the POST data;
  • base64_decode() the content;
  • fwrite() the result into a file using the filename.

That way also you could avoid POSTing all form fields.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...