2014-04-24 66 views
0

我想將圖像轉換爲Base64並放入我的數據庫。 我知道如何將圖像編碼爲Base64,但我不知道如何使用用戶的文件。PHP:編碼圖像Base64本地

因此,用戶可以用<input type="file" /> 「上傳」文件但是,如何在不下載文件並將其存儲在我的服務器的情況下接近該文件?

所以我的文件編碼實際上localy用戶他/她的計算機

感謝

+0

總之:你不能。這是http服務器內置的安全限制。以這種方式上傳的每個文件都將被保存到一個臨時文件中,除了訪問該臨時文件來處理文件數據外,沒有其他辦法可以做到。這是有目的的。 – arkascha

+0

爲什麼你想在_client_一側進行編碼?由於用戶可能不願意理解並執行此操作,因此您必須在腳本級別(javascript)自動執行此操作,但_why_? – arkascha

+0

@arkascha這不是由Web服務器完成的,它是將上傳的文件保存到臨時路徑的php模塊。 –

回答

0

的BLOB數據類型是最適合存儲文件。

,如果你不希望將文件保存到數據庫中,但只讀它,使用:

<form method="post" enctype="multipart/form-data"> 
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box"> 
<tr> 
<td width="246"> 
<input type="hidden" name="MAX_FILE_SIZE" value="2000000"> 
<input name="userfile" type="file" id="userfile"> 
</td> 
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td> 
</tr> 
</table> 
</form> 

這裏
<?php 
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) 
{ 
$fileName = $_FILES['userfile']['name']; 
$tmpName = $_FILES['userfile']['tmp_name']; 
$fileSize = $_FILES['userfile']['size']; 
$fileType = $_FILES['userfile']['type']; 

$fp  = fopen($tmpName, 'r'); 
$content = fread($fp, filesize($tmpName)); 
$content = addslashes($content); 
fclose($fp); 

$內容有文件內容

+0

BLOB數據類型不適合此項目。因爲我想保持我的數據庫儘可能小(在存儲中)。 – Thom

+0

編輯我的答案。請檢查 – Guns

+1

@ user3322384 Base64編碼文件佔用更多空間;如果你想保持你的數據庫儘可能小,*不要*存儲圖像。 –

0

對圖像進行編碼爲Base64可以使用的file_get_contents讀取圖像文件:

$imageBinaryString = file_get_contents('/image/file/path.png'); 

http://us1.php.net/file_get_contents

然後使用Base64編碼:

$base64_imageString = base64_encode($imageBinaryString); 

然後,您可以將數據庫存儲在類型爲text或varchar的列中。

0
<input type="file" name="icon" /> 

現在嘗試使用下面的代碼。

$base = $_REQUEST['icon']; 
$binary = base64_decode($base); 
header('Content-Type: bitmap; charset=utf-8'); 
$file = fopen('upload/imagename.png', 'wb'); 
$imagename = 'path_to_image_/images.png'; 
fwrite($file, $binary); 
fclose($file);