Noor Abdi Noor Abdi - 25 days ago 5
Javascript Question

Uploading image file through jquery with php

I have been trying to upload an image to my server from jquery to php, but the uploaded content is always invalid image. I could not identify the error whether I was encoding or decoding it wrong. Please assist. Thanks.
Jquerycode


$("input[type=file]").change(function(event) {
$.each(event.target.files, function(index, file) {
var reader = new FileReader();
reader.onload = function(event) {
var object = {};
object.filename = document.querySelector('input[type=file]').files[0]['name'];;
object.data = encodeURI(event.target.result);
object.filetype = document.querySelector('input[type=file]').files[0]['type'];
files.push(object);
};
reader.readAsDataURL(file);
});
});

$("form").submit(function(form) {
$.each(files, function(index, file) {
$.ajax({url: "handle.php",
type: 'POST',
data: {fileName: file.filename, data: file.data, fileType: file.filetype},
success: function(data) {
$('#data').html(data);
}
});
});
files = [];
form.preventDefault();
});


PHPCODE:


if(isset($_POST["data"]) || isset($_POST["fileName"])){
$data = $_POST["data"];
$fileName = $_POST["fileName"];
$fileType = $_POST["filetype"];

$replace = "data:".$fileType.";base64,";
$filedata = str_replace($replace, "", $data);//echo $filedata;
$decodedData = urldecode($filedata); //echo $decodedData;

$fp = fopen('uploads/'.$fileName, "w");
fwrite($fp, $decodedData);
fclose($fp);
}

Answer

First make sure you get the base64 code on server e.g you can echo etc. Then assuming your image base64 code was in $_POST['image']

$data = $_POST['image']
$data = str_replace('data:image/png;base64,', '', $data);

$data = base64_decode($data); // base64 decoded image data

$source_img = imagecreatefromstring($data);

$imageSave = imagejpeg($source_img, $file, 10);

imagedestroy($source_img);

Using above lines you can save image as file from base64