Reputation: 137
I have a form, which contents two inputs one hidden with name="action" and second with name="avatar" type="file". After user choose the file in the avatar input the image converts to blob. How can I post the blob like it was loaded as a file and after submited?
Form:
<form enctype="multipart/form-data" method="post" id="avatarform">
<input type="hidden" name="action" value="save" />
<input id="coolButton" name="avatar" type="file" accept="image/*" class="form-control" placeholder="">
</form>
I have try:
var fd = new FormData();
fd.append('action', 'save');
fd.append('avatar', file.name);
fd.append('data', blob);
$.ajax({
type: 'POST',
url: '/',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
php controller:
if ($_FILES['avatar']['name']) {
if ($profile->avatar==1) {
unlink('/images/avatars/'.$profile->avatar);
$profile->avatar=0;
}
$filename="avatar_".$user_id.'.'.pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION);
move_uploaded_file($_FILES['avatar']['tmp_name'],$_SERVER['DOCUMENT_ROOT'] ."/images/avatars/".$filename);
$profile->avatar=$filename;
}
But php controller does not save it. If I use form without script wich converts image to blob - it works good and save the file.
Upvotes: 1
Views: 7204
Reputation: 137
I have updated script
fd.append('blob', blob.replace("data:image/png;base64,", "")
fd.append('ext', "jpg") // send ext of uploaded file
And php controller
if ($_POST['blob']) {
if ($profile->avatar==1) {
unlink('/images/avatars/'.$profile->avatar);
$profile->avatar=0;
}
$file = base64_decode($_POST['blob']);
$filename="avatar_".$user_id.'.'.$_POST['ext'];
file_put_contents($_SERVER['DOCUMENT_ROOT'] ."/images/avatars/".$filename, $file);
$profile->avatar=$filename;
}
Upvotes: 1