Here is a complete example of browsing an image file .jpg
and converting it into base64 byte format and sending it to server.
Server script php
will decode and save image to server.
HTML
<html>
<head>
<script src="jquery.js"></script>
<script>
function getBase64Image()
{
var files = document.getElementById('file1').files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{
// Only process image files.
if (!f.type.match('image.*'))
{
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
var str = e.target.result;
var res = str.replace("data:image/jpeg;base64,","");
var res = str.replace("data:base64,","");
$("#tbx_base64").val(res);
console.log(e.target)
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
function submitForm(){
//SENDING IMAGE FILE WITH JSON OBJECT. YOU CAN ALSO SEND WITHOUT JSON OBJECT.
var o = {};
o.name = "Test";
o.arr = ["lucky_no":323];
o.upload_image = $("#tbx_base64").val();
$.post("http://localhost/jquery_multiple_file_upload/upload.php/", {o:o}, function(data){
alert(data)
});
}
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post" id="form_test">
<input id="file1" type="file" onChange="getBase64Image()" />
<textarea id="tbx_base64" style="display:none"></textarea> <!-- TEXTAREA IS HIDE. AS IT IS ONLY USED TO HOLD BYTE DATA -->
<input type="button" value="Upload File" id="upload" onClick="submitForm();" />
</form>
</body>
</html>
PHP
<?php
$image_byte_code = $_REQUEST['o'];
$content = base64_decode($image_byte_code['upload_image']);
$im = imagecreatefromstring($content);
if ($im !== false) {
header('Content-Type: image/jpeg');
imagejpeg($im, "uploads/1.jpg");
imagedestroy($im);
}
else
{
echo 'An error occurred.';
}
?>