2

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 Facebook directly -- without hosting the image on a server.

The problem we're facing is how to convert the base64-encoded data from toDataURL() into the multipart/form-data that Facebook expects. Is this possible on the client side with JavaScript and jQuery.post()? If not, we can resort to saving the image on a server first but prefer bypassing this step if possible and doing everything from the client.

This is for a PhoneGap app.

Community
  • 1
  • 1
Crashalot
  • 33,605
  • 61
  • 269
  • 439

2 Answers2

2

Uploading a canvas as a picture on the server is possible. I did a test 2 years ago, you can look up the code: http://standupweb.net/canvas/swSaveCanvas.php

That was using mootools, but it is really not needed there, everything in the save function is native JS code.

Integrating that with facebook should not be a big problem

standup75
  • 4,734
  • 6
  • 28
  • 49
  • Cool, thanks @standup75. Do you know if this is possible with jQuery.post()? Otherwise, writing the AJAX request like you did will work, but we prefer to funnel everything through jQuery.post() if possible. – Crashalot Apr 18 '12 at 18:32
  • I guess not, the save funciton is building the multipart request "by hand" – standup75 Apr 18 '12 at 18:36
  • @standup75 Why not? Wouldn't sending that multipart request body using $.post work by setting the contentType? – pradeek Apr 19 '12 at 04:33
  • If you use $.post, jQeury is taking care of posting the variables in the body of the request for you, that conflicts with the way it is done here, cause we're building the body of the request by formatting ourselves an ISO 8859 string – standup75 Apr 19 '12 at 18:56
  • thanks @pradeek and standup75, but it seems like it doesn't work with Facebook unfortunately. – Crashalot Apr 21 '12 at 20:38
  • The link is dead. – cchamberlain May 09 '17 at 19:27
1

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);
hungneox
  • 9,333
  • 12
  • 49
  • 66