2

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 submitted?

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 the PHP controller does not save it. If I use form without script which converts image to blob - it works good and saves the file.

2
  • please provide some more code Commented Jul 28, 2016 at 8:16
  • file.name = name of loaded file; blob = data:image/png;base64,..............[binarycode]; Only this part of code makes POST action, other code updates the blob. I just want to get the method to submit the form with updated image. Commented Jul 28, 2016 at 8:27

1 Answer 1

1

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;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Hi mike, can I get you to make a example of the full code? can't get it to work and im not sure what is wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.