Hello guys I successfully found a method that claims to make a file input file into a base 64 string in JavaScript so I successfully sent that base 64
string by JSON via AJAX and the base 64 encoded string looks like this sent in the JSON method "photo":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wB etc...."
So when the base 64 string arrives in the PHP file. The PHP does it's magic and successfully store a file in the targeted folder where I want the file to be at so when I look in that folder there is a file but
when I try to open the photo file to view it the photo viewer app says something like, image.jpg it looks like we don't support this file format and in other photo viewer apps it will say something
similar to that so what have I done wrong?
Here is my code
index.php
<style>
#photo-input{
display: block;
margin-bottom: 50px;
}
</style>
<script>
document.addEventListener('DOMContentLoaded',function(){
document.querySelector('#submit').addEventListener('click',function(){
var photo_input= document.querySelector('#photo-input').files[0];
var reader = new FileReader();
reader.readAsDataURL(photo_input);
reader.onload = function (){
var photo_input_result= reader.result;
sendUploadInfo(photo_input_result);
}
});
function sendUploadInfo(photo_input_result){
var photo= photo_input_result;
var upload_info = {
first_name: "John",
last_name: "Smith",
photo: photo
};
var upload_info_json_object= 'upload_info_json_object='+JSON.stringify(upload_info);
var xhr= new XMLHttpRequest();
xhr.onreadystatechange= function(){
if(xhr.readyState == 4){
document.querySelector('#output').innerHTML= xhr.responseText;
}
}
xhr.open('POST','x');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(upload_info_json_object);
}
});
</script>
<input type='file' id='photo-input'>
<button id='submit'>Send JSON data</button>
<div id='output'></div>
x.php
<?php
$upload_info_json_object = json_decode($_POST['upload_info_json_object']);
$first_name= $upload_info_json_object->first_name;
$last_name= $upload_info_json_object->last_name;
$photo= $upload_info_json_object->photo;
base64_decode($photo);
$path= $_SERVER['DOCUMENT_ROOT'].'/send-json-data-by-ajax/object-based/with-file/2/images/image.jpg';
file_put_contents($path, $photo);
?>
<h1><?php echo $first_name.' '.$last_name.' just uploaded a photo.'; ?></h1>
What I have tried:
Google search other website and other help sites no luck yet for helpful answers.