Ajax File Upload using Codeigniter

2019-03-22 07:44发布

问题:

I'm trying to upload an image using codeigniter and ajax. I already have the ajax method to insert the field values to the DB, what's the easiest and simplest way to upload my file. Here's the JQuery custom function:

(function($){
    jQuery.fn.ajaxSubmit =
        function() {
            $(this).submit(function(event) {
                event.preventDefault();
                var url = $(this).attr('action');                       
                var data = $(this).serialize();

                $.ajax({
                    url: url,
                    type: "POST",
                    data: data,
                    dataType: "html",
                    success: function(msg) {
                               $('#main').html(msg);
                             }
                       });

                 return this;
             });
         };
})(jQuery);

I call it like this:

$(document).ready(function() {    
    $('#myForm').ajaxSubmit();
});

The function works fine, the data gets inserted in the database and I even have some directories that get created in the model before uploading the image, they are created but the image is not uploaded at all.

I know I need to use a hidden Iframe to do the job, but I dont quite know how to integrate that in my code.

回答1:

I created custom Ajax File Uploader using CodeIgniter, jQuery and Malsup form plugin. Here is the HTML and Javascript/CSS code. It also support multiple file upload and Progress.

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Ajax UP Bar</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
        <script type="text/javascript">
            $(document).ready( function() {
                $('form').submit( function() {
                    var bar = $('.bar');
                    var percent = $('.percent');
                    var status = $('#status');
                    $(this).ajaxForm({
                        beforeSend: function() {
                            status.html();
                            var percentVal = '0%';
                            bar.width(percentVal)
                            percent.html(percentVal);
                        },
                        uploadProgress: function(event, position, total, percentComplete) {
                            var percentVal = percentComplete + '%';
                            bar.width(percentVal)
                            percent.html(percentVal);
                        },
                        complete: function(xhr) {
                            status.html(xhr.responseText);
                        }
                    });
                });
            });
        </script>
    </head>

    <body>

        <form method="post" action="<?php echo base_url('users/upload/'); ?>" enctype="multipart/form-data">
            <label for="upload">Select : </label>
            <input type="file" name="upload[]" id="upload" multiple="multiple" />
            <input type="submit" name="fsubmit" id="fsubmit" value="Upload" />
        </form>

        <div class="progress">
            <div class="bar"></div >
            <div class="percent">0%</div >
        </div>

        <div id="status"></div>

    </body>
</html>
<style>
    body { padding: 30px }
    form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }

    .progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
    .bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
    .percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>

In CodeIgniter Controller :

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Users extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    public function upload()
    {
        if (isset($_FILES['upload']['name'])) {
            // total files //
            $count = count($_FILES['upload']['name']);
            // all uploads //
            $uploads = $_FILES['upload'];

            for ($i = 0; $i < $count; $i++) {
                if ($uploads['error'][$i] == 0) {
                    move_uploaded_file($uploads['tmp_name'][$i], 'storage/' . $uploads['name'][$i]);
                    echo $uploads['name'][$i] . "\n";
                }
            }
        }
    }

}

Hope this helps you. Thanks!!