Using fileuploader.js in codeigniter along with csrf in ajax

风格不统一 提交于 2019-12-06 12:23:08

问题


How do I use fileuploader.js in Codeigniter with csrf, in ajax?

I am using the images_crud library http://www.web-and-development.com/image-crud-an-automatic-multiple-image-uploader-for-codeigniter/

I keep getting

The action you have requested is not allowed.

Added..

I have added the create method in the controller :

/**
 * pages form
 */
public function create(){

    if(!isset($this->data['output'])){
        $this->data = array_merge($this->data, 
                        array(  'output'    => '' , 
                                'js_files'  => array() , 
                                'css_files' => array()
                            )
                        );
    }


    //-------------------------
    //for file uploading
    $image_crud = new image_CRUD();

    $image_crud->set_primary_key_field('id');
    $image_crud->set_url_field('filename');
    $image_crud->set_table('news')
        ->set_image_path('public/documents');

    $output = $image_crud->render();

    $this->data['output']=$output->output;
    $this->data['js_files']=$output->js_files;
    $this->data['css_files']=$output->css_files;
    //-------------------------


    //display
    $this->load->view('templates/admin_header');
    $this->load->view('admin/index.php');
    $this->load->view('admin/create_pages.php', $this->data);
    $this->load->view('templates/admin_footer');
}

And the create_pages in view :

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
<?php echo validation_errors()?>

<?php 
foreach($css_files as $file): ?>
<link type="text/css" rel="stylesheet" href="<?php echo $file; ?>" />
<?php endforeach; ?>
<?php foreach($js_files as $file): ?>
<script src="<?php echo $file; ?>"></script>
<?php endforeach; ?>

<?php echo form_open(site_url('admin/pages/save'),array('style'=>'width:700px;'))?>

<label>
    Title
    <input type='text' name='title' value='<?php echo @$title?>' />
</label>
<br/>

content :
<textarea name="content" id="content" >
    <?php echo @$content?>
</textarea>
<br/>

<?php echo $output?>

<input type='submit' name='submit' value='save' />
</form>

I have added image_crud.php and image_moo.php in the library.

I am getting 500 Internal Server Error with the url being http://example.com/mole/pages/create/upload_file?qqfile=1355936206.9151.jpg

which I wanted to be http://example.com/mole/admin/pages/create/upload_file?qqfile=1355936206.9151.jpg

I am not sure why the fileuploader.js is taking a different url for uploading.

Added

Well, I have not made much changes to the codings avilaible from http://www.web-and-development.com/image-crud-an-automatic-multiple-image-uploader-for-codeigniter/

$(function(){
<?php if ( ! $unset_upload) {?>
    createUploader();
<?php }?>
    loadColorbox();
});
function loadColorbox()
{
$('.color-box').colorbox({
    rel: 'color-box'
});
}
function loadPhotoGallery(){
$.ajax({
    url: '<?php echo $ajax_list_url?>',
    dataType: 'text',
    data:$('input[type=hidden]').eq(1).prop('name')+':'+$('input[type=hidden]').eq(1).prop('value'),
    beforeSend: function()
    {
        $('.file-upload-messages-container:first').show();
        $('.file-upload-message').html("<?php echo $this->l('loading');?>");
    },
    complete: function()
    {
        $('.file-upload-messages-container').hide();
        $('.file-upload-message').html('');
    },
    success: function(data){
        $('#ajax-list').html(data);
        loadColorbox();
    }
});
}
function createUploader(){
        var uploader = new qq.FileUploader({
            element: document.getElementById('file-uploader-demo1'),
            template: '<div class="qq-uploader">' +
                '<div class="qq-upload-drop-area"><span><?php echo $this->l("upload-drop-area");?></span></div>' +
                '<div class="qq-upload-button"><?php echo $this->l("upload_button");?></div>' +
                '<ul class="qq-upload-list"></ul>' +
                '</div>',
            fileTemplate: '<li>' +
                '<span class="qq-upload-file"></span>' +
                '<span class="qq-upload-spinner"></span>' +
                '<span class="qq-upload-size"></span>' +
                '<a class="qq-upload-cancel" href="#"><?php echo $this->l("upload-cancel");?></a>' +
                '<span class="qq-upload-failed-text"><?php echo $this->l("upload-failed");?></span>' +
                '</li>',
            action: '<?php echo $upload_url?>',
            debug: true,
            onComplete: function(id, fileName, responseJSON){
                loadPhotoGallery();
            }
        });
}
function saveTitle(data_id, data_title)
{
    $.ajax({
        url: '<?php echo $insert_title_url; ?>',
        type: 'post',
        data: {primary_key: data_id, value: data_title},
        beforeSend: function()
        {
            $('.file-upload-messages-container:first').show();
            $('.file-upload-message').html("<?php echo $this->l('saving_title');?>");
        },
        complete: function()
        {
            $('.file-upload-messages-container').hide();
            $('.file-upload-message').html('');
        }
        });
}

回答1:


here you have two problems.

First: you need to set the csrf token with every ajax request. which is simple.

Second: you need to set the csrf token for when uploading. which is impossible.

But sure you have other alternatives here. DON'T Worry!.

each method like edit title or delete etc.. you can solve it like this:

in your list.php at the very first:

    $this->set_css('assets/image_crud/css/fileuploader.css');
    $this->set_css('assets/image_crud/css/photogallery.css');
    $this->set_css('assets/image_crud/css/colorbox.css');

    $this->set_js('assets/image_crud/js/jquery-1.8.2.min.js');
    $this->set_js('assets/image_crud/js/jquery-ui-1.9.0.custom.min.js');
    $this->set_js('assets/image_crud/js/fileuploader.js');
    $this->set_js('assets/image_crud/js/jquery.colorbox-min.js');
    $CI =& get_instance(); // create codeigniter reference instance.

Then:

function saveTitle(data_id, data_title)
{
        $.ajax({
            url: '<?php echo $insert_title_url; ?>',
            type: 'post',
            data: {primary_key: data_id, value: data_title,
            '<?php echo $CI->security->get_csrf_token_name(); ?>':'<?php echo $CI->security->get_csrf_hash(); ?>'},
            beforeSend: function()
            {
                $('.file-upload-messages-container:first').show();
                $('.file-upload-message').html("<?php echo $this->l('saving_title');?>");
            },
            complete: function()
            {
                $('.file-upload-messages-container').hide();
                $('.file-upload-message').html('');
            }
            });
}

simple solution. just adding the csrf_token_name and csrf_hash_value.

now for the second problem I said that it's impossible because the qq.fileuploader uses $_GET and not $_POST, so the property params they offer just adds a get argument for you which will not be parsed by csrf_verify() method. how to solve it: simply go to your config/config.php and add the following code to the end of it:

if(stripos($_SERVER["REQUEST_URI"],'/upload_file') === FALSE)
{
    $config['csrf_protection'] = TRUE;
}
else
{
    $config['csrf_protection'] = FALSE;
} 

which will disable the uploading csrf checking for you ( it will be disabled just when uploading ) and it will re-enable it with the next request.

I have tested this code and it's working 100%. :)

Update: the main problem consists of that the developer of image_crud has not considered multipart encoded request ( as I can see from the new results). and he is using an old version of fineuploader. the problem is solved by fineuploader 3.0+ but not yet in image_crud which is making problems when using multipart encoded request.

Hope that I helped.




回答2:


The author of image_crud has just pushed out a new version that utilizes the latest version of Fine Uploader. Problems with IE and other issues you may have run into should be fixed in the newest version. You should be able to make use of csrf tokens now without minimal reconfiguration.



来源:https://stackoverflow.com/questions/14294672/using-fileuploader-js-in-codeigniter-along-with-csrf-in-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!