How can I upload a photo to Facebook using Haskell?

203 Views Asked by At

I am using Happstack, and I am trying to upload a photograph to Facebook using the Facebook Graph API.

I can successfully post a message to Facebook. I can use url, however I am trying to do this with the source parameter.

I have a ByteString of PNG data, but I can't seem to pass it along to Facebook.

I am using the fb Haskell library.

The functions that I have created to do this are:

performPost :: String -> IO Response
performPost code = do
    x <- BS.readFile "test.png"
    performFBAction $ do
        postToFB (BS.unpack x) code =<< getToken url2 code
        return $ toResponse postFB

postToFB :: (MonadResource m, MonadBaseControl IO m) => String -> String -> FB.UserAccessToken -> FB.FacebookT FB.Auth m FB.Id
postToFB dataString code token = FB.postObject "me/photos" [args "message" "Test Post Pls Ignore",
                                                            args "source" dataString] token

The error that I receive is:

The error was "StatusCodeException (Status {statusCode = 400, statusMessage = "Bad Request"}) [("Content-Type","text/html; charset=utf-8"),("Date","Thu, 29 Jan 2015 05:06:00 GMT"),("Connection","close"),("Content-Length","3121")] (CJ {expose = []})

What am I doing wrong? The Graph API states that the source parameter should be of type form data, but I have so far been unsuccessful in trying to convert it to such.

Thanks!

2

There are 2 best solutions below

5
On BEST ANSWER

Please check whether the photo's content is encoded correctly. It need to be multipart/form-data as stated on

0
On

What Tobi said is correct. The code to correctly perform this operation is:

postPhoto :: FB.UserAccessToken -> IO Response
postPhoto (FB.UserAccessToken _ b _) = withSocketsDo $ withManager $ \m -> do
    fbpost <- parseUrl $ "https://graph.facebook.com/v2.2/me/photos?access_token=" ++ T.unpack b
    flip httpLbs m =<<
        (formDataBody [partBS "message" "Test Message",
                       partFileSource "graph" "graph.png"]
                      fbpost)
    return $ toResponse postFB

Enjoy!