我必须上传从 Android 应用程序接收到的 Base64 编码图像。我正在使用 php codeigniter 框架。 在论坛搜索时,此链接的问题How to upload base64encoded image in codeigniter和我的一样,但是那里的解决方案不适合我。
这是我编写的代码:
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 以省略该检查,但这可能会使以后升级框架变得困难。
将 $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'], );
修改上传库。您可以使用 codeigniter 的内置 way of Extending Native Libraries ,并定义一个 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 )
并在您的 Controller 中,使用以下参数调用 do_upload():
$this->upload->do_upload('userfile', true);