Noor Abdi Noor Abdi - 1 year ago 98
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.

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

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


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

Answer Source

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


Using above lines you can save image as file from base64

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download