[英]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來忽略該檢查,但是這可能會使以后升級框架變得困難。
將$ 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的擴展本機庫的內置方式 ,定義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.