繁体   English   中英

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

[英]Unable to upload a base64 encoded image using Codeigniter

我必须上传从Android应用程序接收到的base64编码图像。 我正在使用php codeigniter框架。 在论坛中搜索时,此链接上的问题如何在codeigniter中上传base64encoded图像与我的相同,但那里的解决方案对我不起作用。

这是我编写的代码:

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 / libraries / 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM