Unable to upload a base64 encoded image using Codeigniter

前端 未结 2 1052
情深已故
情深已故 2021-01-14 01:30

I have to upload a base64 encoded image that i am receiving from android application. I am using php codeigniter framework. While searching through the forum, the question

2条回答
  •  迷失自我
    2021-01-14 01:55

    The error is occurring because codeigniter's upload library will look into the $_FILES superglobal to and search for a index you give it at the do_upload() call.

    Furthermore (at least in version 2.1.2) even if you would set up the $_FILES superglobal to mimic the behaviour of a file upload it wouldn't pass because the upload library uses is_uploaded_file to detect exacly that kind of tampering with superglobals. You can trace the code in system/libraries/Upload.php:134

    I'm afraid that you will have to re-implement size checking and file renaming and moving (I would do this) or you can modify codeigniter to omit that check, but it could make upgrading the framework later difficult.

    1. Save the $image variable's content to a temporary file, and set up the $_FILES to look like this:

       $temp_file_path = tempnam(sys_get_temp_dir(), 'androidtempimage'); // might not work on some systems, specify your temp path if system temp dir is not writeable
       file_put_contents($temp_file_path, base64_decode($_POST['imageString']));
       $image_info = getimagesize($temp_file_path); 
       $_FILES['userfile'] = array(
           'name' => uniqid().'.'.preg_replace('!\w+/!', '', $image_info['mime']),
           'tmp_name' => $temp_file_path,
           'size'  => filesize($temp_file_path),
           'error' => UPLOAD_ERR_OK,
           'type'  => $image_info['mime'],
       );
      
    2. Modify the upload library. You can use codeigniter's built in way of Extending Native Libraries, and define a My_Upload (or your prefix) class, copy-paste the do_upload function and change the following lines:

      public function do_upload($field = 'userfile')
      

      to:

      public function do_upload($field = 'userfile', $fake_upload = false)
      

      and the:

      if ( ! is_uploaded_file($_FILES[$field]['tmp_name']) )
      

      to:

      if ( ! is_uploaded_file($_FILES[$field]['tmp_name']) && !$fake_upload )
      

      and in your controller, call do_upload() with the flowing parameters:

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

提交回复
热议问题