无法使用Codeigniter上载base64编码的图像


Unable to upload a base64 encoded image using Codeigniter

我必须上传一个从android应用程序接收的base64编码图像。我使用的是php代码点火器框架。在论坛上搜索时,这个链接上的问题如何在codeigniter中上传base64编码的图像与我的问题相同,但那里的解决方案对我不起作用。

这是我写的代码:

private function _save_image() {
    $image = base64_decode($_POST['imageString']);
    #setting the configuration values for saving the image
    $config['upload_path'] = FCPATH . 'path_to_image_folder';
    $config['file_name'] = 'my_image'.$_POST['imageType'];
    $config['allowed_types'] = 'gif|jpg|jpeg|png';
    $config['max_size'] = '2048';
    $config['remove_spaces'] = TRUE;
    $config['encrypt_name'] = TRUE;

    $this->load->library('upload', $config);
    if($this->upload->do_upload($image)) {
        $arr_image_info = $this->upload->data();
        return ($arr_image_info['full_path']);
    }
    else {
        echo $this->upload->display_errors();
        die();
    }
}

我得到"你没有选择一个文件上传"

谢谢你抽出时间。

发生此错误是因为codeigniter的上传库将查找$_FILES的超全局,并搜索您在do_upload()调用中为其提供的索引。

此外(至少在2.1.2版本中),即使您将$_FILES超级全局设置为模拟文件上传的行为,它也不会通过,因为上传库使用is_uploaded_file来检测超级全局的这种篡改。您可以在system/librarys/Upload.php中跟踪代码:134

恐怕您将不得不重新实现大小检查、文件重命名和移动(我会这样做),或者您可以修改codeigniter以省略该检查,但这可能会使以后升级框架变得困难。

  1. 将$image变量的内容保存到一个临时文件中,并将$_FILES设置为如下所示:

     $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. 修改上传库。您可以使用codeigniter以扩展本地库的方式构建的,并定义My_Upload(或前缀)类,复制粘贴do_Upload函数并更改以下行:

    public function do_upload($field = 'userfile')
    

    至:

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

    和:

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

    至:

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

    在您的控制器中,使用流动参数调用do_upload():

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

您知道,如果您正在接收Base64编码的图像,作为字符串,那么您不需要使用Upload类。

相反,您只需要使用base64_decode对其进行解码,然后使用fwrite/file_put_contents保存解码后的数据。。。

$img = imagecreatefromstring(base64_decode($string)); 
if($img != false) 
{ 
   imagejpeg($img, '/path/to/new/image.jpg'); 
}  

信用:http://board.phpbuilder.com/showthread.php?10359450-RESOLVED-Saving-Base64-image。