How's the codeigniter with ajax downloading pictures on the server?



  • Example without ajax

    <html>
    <head>
    <title>Форма загрузки</title>
    </head>
    <body>
    

    <?php echo $error;?>

    <?php echo form_open_multipart('upload/do_upload');?>

    <input type="file" name="userfile" size="20" />

    <br /><br />

    <input type="submit" value="upload" />

    </form>

    </body>
    </html>

    Controller

    class Upload extends Controller {

    function Upload()
    {
        parent::Controller();
        $this->load->helper(array('form', 'url'));
    }
    

    function index()
    {
    $this->load->view('upload_form', array('error' => ' ' ));
    }

    function do_upload()
    {
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '100';
    $config['max_width'] = '1024';
    $config['max_height'] = '768';

    $this-&gt;load-&gt;library('upload', $config);
    
    if ( ! $this-&gt;upload-&gt;do_upload())
    {
        $error = array('error' =&gt; $this-&gt;upload-&gt;display_errors());
    
        $this-&gt;load-&gt;view('upload_form', $error);
    }   
    else
    {
        $data = array('upload_data' =&gt; $this-&gt;upload-&gt;data());
    
        $this-&gt;load-&gt;view('upload_success', $data);
    }
    

    }


    ? ation



  • In fact, I've decided. form:

     <form role="form" action="">
                        <fieldset class="form-group">
                                <label for="title">Заголовок</label>
                                <input type="text" class="form-control" id="title" name="title" required="" placeholder="Введіть Заголовок">
                        </fieldset>
                        <fieldset class="form-group">
                            <label for="brief_description">Короткий текст (початок)</label>
                            <textarea class="form-control" rows="5" id="brief_description" name="brief_description" maxlength="160"></textarea>
                        </fieldset>
                        <fieldset class="form-group">
                            <label for="brief_description">Повний текст (продовження)</label>
                            <textarea class="form-control" rows="5" id="full_description" name="full_description" ></textarea>
                        </fieldset>
                        <fieldset class="form-group">
                            <label for="InputFile">File input</label>
                            <input type="file" id="InputFile" name="image" multiple="multiple" size="20">
                            <div class="help-block">Example block-level help text here.</div>
                            <button type="button" name="send_img" id="send_img" value="Send_img" class="btn btn-labeled btn-success">
                                <span class="btn-label"><i class="glyphicon glyphicon-ok"></i></span>Завантажити</button>
                        </fieldset>
                        <div class="text-center">
                            <button type="button" name="send_data" id="send_data" value="Send" class="btn btn-labeled btn-success">
                                <span class="btn-label"><i class="glyphicon glyphicon-ok"></i></span>Зберегти</button>
                        </div>
                    </form>
    

    js:

    $("#InputFile").on("change", function(){
                   files = this.files;
                   //alert(file);
    
            });
            $('#send_img').click(function( event ){
                    event.stopPropagation(); // Остановка происходящего
                    event.preventDefault();  // Полная остановка происходящего
    
                    // Создадим данные формы и добавим в них данные файлов из files
    
                    var data = new FormData();
                    $.each( files, function( key, value ){
                        data.append( key, value );
                    });
    
                    // Отправляем запрос
    
                    $.ajax({
                        url: "&lt;?=base_url()?&gt;news/upload_photo",
                        type: 'POST',
                        data: data,
                        cache: false,
                        dataType: 'html',
                        processData: false, // Не обрабатываем файлы (Don't process the files)
                        contentType: false, // Так jQuery скажет серверу что это строковой запрос
                        success: function( data ){
                            $(".help-block").empty().append(data);
                        },
                        error: function( jqXHR, textStatus, errorThrown ){
                            console.log('ОШИБКИ AJAX запроса: ' + textStatus );
                        }
                    });
                });
    

    control function:

    public function upload_photo(){

        if(isset($_FILES)){
            //print_r($_FILES);
            $config['upload_path']          = './img/node/';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 5000;
            $config['encrypt_name']         = TRUE;
    
            $this-&gt;load-&gt;library('upload', $config);
            $this-&gt;upload-&gt;initialize($config);
    
            $this-&gt;upload-&gt;do_upload('0');
            $data = $this-&gt;upload-&gt;data();
            $html = '&lt;div class="alert alert-success" role="alert"&gt;Файл: '.$data['orig_name'].' успішно завантаженний! '."&lt;p&gt;&lt;br&gt;&lt;img src='".base_url().'/img/node/'.$data['file_name']."'&gt;&lt;/p&gt;&lt;/div&gt;";
            //print_r($data);
            echo $html;
        }
    }
    




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2