Question

I want to convert a image to Base64 and put in into my database. I know how to encode a image to Base64, but I dont know how to use a file from a user.

So the user can "upload" a file with <input type="file" /> But how can I approach that file without download the file and store it at my server?

So i encode the file actually localy on the user his/her computer

Thanks

Était-ce utile?

La solution

The BLOB datatype is best for storing files.

if you do not want to save the file to the database, but just read it, use:

<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);

$content here has the file content

Autres conseils

To encode an image to base64 you can use file_get_contents to read the image file:

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

http://us1.php.net/file_get_contents

Then base64 encode:

$base64_imageString = base64_encode($imageBinaryString);

You can then store in database in a column with type text or varchar.

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

Now try with below code.

 $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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top