2

I have an ajax file upload with jquery. It always shows The action you have requested is not allowed. Helper arrays html, url, file, form are added. I tried many ways, but gets the same result.

browser console

browser console for upload_data

Here is my code

Controller Functions

 function demo() {
          $this->load->view('file_upload_ajax', NULL);
      }

      function upload_file() {

          //upload file
          $config['upload_path'] = 'uploads/';
          $config['allowed_types'] = '*';
          $config['max_filename'] = '255';
          $config['encrypt_name'] = TRUE;
          $config['max_size'] = '1024'; //1 MB
          echo $_FILES['file']['name'];
          if (isset($_FILES['file']['name'])) {
              if (0 < $_FILES['file']['error']) {
                  echo 'Error during file upload' . $_FILES['file']['error'];
              } else {
                  if (file_exists('uploads/' . $_FILES['file']['name'])) {
                      echo 'File already exists : uploads/' . $_FILES['file']['name'];
                  } else {
                      $this->load->library('upload', $config);
                      if (!$this->upload->do_upload('file')) {
                          echo $this->upload->display_errors();
                      } else {
                          echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
                      }
                  }
              }
          } else {
              echo 'Please choose a file';
          }
      }

View file: file_upload_ajax.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Beep Check</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="<?php echo base_url().'js'?>/beep.js"></script>

    </head>
    <body>
        <p id="msg"></p>
        <input type="file" id="file" name="file" />
        <button id="upload">Upload</button>
    </body>
</html>

beep.js

$(document).ready(function() {

  $('#upload').on('click', function () {
      var file_data = $('#file').prop('files')[0];
      var form_data = new FormData();
      form_data.append('file', file_data);
      $.ajax({           
          url: base_url +"beep/upload_file",
          dataType: 'text',
          cache: false,
          contentType: false,
          processData: false,
          data: form_data,
          type: 'post',
          success: function (response) {
              $('#msg').html(response); // display success response from the server
          },
          error: function (response) {
              $('#msg').html(response); // display error response from the server
          }
      });
  });

});

config.php

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


$config['base_url'] = '';


//$config['index_page'] = 'index.php';
$config['index_page'] = '';


$config['uri_protocol'] = 'AUTO';



$config['url_suffix'] = '';


$config['language'] = 'english';


$config['charset'] = 'UTF-8';


$config['enable_hooks'] = FALSE;



$config['subclass_prefix'] = 'MY_';



$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';



$config['allow_get_array']      = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger']   = 'c';
$config['function_trigger']     = 'm';
$config['directory_trigger']    = 'd'; // experimental not currently in use


$config['log_threshold'] = 4;


$config['log_path'] = '';


$config['log_date_format'] = 'Y-m-d H:i:s';


$config['cache_path'] = '';


$config['encryption_key'] = 'kccna_mat_1';


$config['sess_cookie_name']     = 'ci_session';
$config['sess_expiration']      = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie']  = FALSE;
$config['sess_use_database']    = FALSE;
$config['sess_table_name']      = 'ci_sessions';
$config['sess_match_ip']        = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update']  = 300;


$config['cookie_prefix']    = "";
$config['cookie_domain']    = "";
$config['cookie_path']      = "/";
$config['cookie_secure']    = FALSE;


$config['global_xss_filtering'] = FALSE;


$config['csrf_protection'] = true;
$config['csrf_token_name'] = 'k4rm4_auth';
$config['csrf_cookie_name'] = 'k4rm4_auth';
$config['csrf_expire'] = 7200;


$config['compress_output'] = FALSE;


$config['time_reference'] = 'local';



$config['rewrite_short_tags'] = FALSE;


$config['proxy_ips'] = '';

Please help me Thanks in advance.

Prasanth
  • 59
  • 2
  • 6

1 Answers1

1

Check your config.php if $config['csrf_protection'] = TRUE; If it is set to true you need to send csrf token with the ajax request.

Add this to your view page.

<input type="hidden" id="hidCSRF" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">

In your js file do the below changes.

$(document).ready(function() {
    $('#upload').on('click', function () {  
        var _csrfName = $('input#hidCSRF').attr('name');
        var _csrfValue = $('input#hidCSRF').val();
        var file_data = $('#file').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        form_data.append(_csrfName, _csrfValue);

        $.ajax({           
            url: base_url +"beep/upload_file",
            dataType: 'text',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            type: 'post',
            success: function (response) {
                $('#msg').html(response); // display success response from the server
            },
            error: function (response) {
                $('#msg').html(response); // display error response from the server
            }
        });
    });
});
Alok
  • 297
  • 3
  • 13
  • in my config.php file $config['csrf_protection'] was TRUE and I changed the code as u provided.But It again shows the same error. – Prasanth Mar 17 '17 at 08:11
  • Can you please share a screenshot of your browser console while you are uploading. Please use chrome's Network. Also share the backend code (CI). – Alok Mar 17 '17 at 08:22
  • Its 500 error means there is error in some part of code. CSRF is now fixed. – Alok Mar 17 '17 at 10:48
  • can you upload screenshot of upload_file. – Alok Mar 17 '17 at 10:49
  • attached the screenshot on direct calling upload_file – Prasanth Mar 17 '17 at 11:05
  • Ok, Can you again upload file. Keep browser console open. Click on "upload_file" under "Name" column in Network tab. A new section will be open with tabs like Headers, Preview, Response etc. Click on Headers and take screenshot of it. Please take full screenshot. So that i can view the post parameters clearly – Alok Mar 17 '17 at 11:18
  • Not able to view full Header section, can you take full header section screenshot. I want to view post param there. You can change the view of console by clicking on the three dots present at the right corner of the console beside "Audits" – Alok Mar 17 '17 at 11:43
  • attached the screenshot with whole header tab – Prasanth Mar 17 '17 at 11:56
  • Have you added this to your file_upload_ajax.php – Alok Mar 17 '17 at 11:59
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/138323/discussion-between-prasanth-and-alok). – Prasanth Mar 17 '17 at 12:01