Upload photo with Facebook Graph API and [removed] convert canvas image to multipart/form-data as POST body?

前端 未结 2 1800
野性不改
野性不改 2021-01-03 12:56

From this SO question on the topic and from our research elsewhere on the web (like this Facebook doc link), it seems possible to upload an image from canvas.toDataURL() to

2条回答
  •  误落风尘
    2021-01-03 13:28

    Basically, You need to remove 'data:image/png;base64' from URI scheme (by using canvas.toDataURL("image/png") for example) and decode it to original form of image source.

    Here is my code. I need to use dojo.toJson because of a weird bug happen with facebook.

    jQuery.post('index.php',{ 
        data : dojo.toJson({
        image_data: img,
        signed_request: signedRequest
     })
    },function(d){
    
    });
    

    And this is PHP

    $data = json_decode($_POST['data']);        
    $message = $data->message;
    $uploadImage = $data->image_data;
    $uploadImage = str_replace('data:image/png;base64,', '', $uploadImage);
    $uploadImage = base64_decode($uploadImage);
    
    $name = uniqid('image_') . '.png';
    file_put_contents('public/images/users/' . $name, $uploadImage);
    
    $image = array(
        'message' => $message,
        'src' => '@' . realpath('public/images/users/' . $name),
    );
    $result = $this->_facebook->uploadPhoto($image);
    

提交回复
热议问题