In order to upload photos to Facebook from the server-side, the Graph API requires you to make a POST request with the image attached as multipart/form-data. Since I couldn’t find any native Scala libraries that make this task easy or intuitive, I went with the battle-tested Apache HttpComponents library.
Since the app was going to upload photos to Facebook in an on-demand fashion, I went with an HTTPClient that could be reused and was able handle multiple requests concurrently.
In this case source is the name of the form field whose value is the image file. The next step is to create a POST request and execute it using our httpClient.
importjava.io.Fileimportjava.net.URIimportorg.apache.http.client.methods.{HttpPost,CloseableHttpResponse}importorg.apache.http.client.protocol.HttpClientContextimportorg.apache.http.entity.mime.MultipartEntityBuilderimportorg.apache.http.entity.mime.content.{StringBody,FileBody}importorg.apache.http.entity.ContentTypeimportorg.apache.http.util.EntityUtilsimportorg.apache.http.impl.conn.PoolingHttpClientConnectionManagerimportorg.apache.http.impl.client.HttpClientsimportscala.util.TryobjectUploader{lazyvalhttpClient={valconnManager=newPoolingHttpClientConnectionManager()HttpClients.custom().setConnectionManager(connManager).build()}defuploadToFacebook(file:File,accessToken:String):Try[String]={valuri=newURI("https://graph.facebook.com/me/photos")Try({// Create the entityvalreqEntity=MultipartEntityBuilder.create()// Attach the filereqEntity.addPart("source",newFileBody(file))// Attach the access token as plain textvaltokenBody=newStringBody(accessToken,ContentType.TEXT_PLAIN)reqEntity.addPart("access_token",tokenBody)// Create POST requestvalhttpPost=newHttpPost(uri)httpPost.setEntity(reqEntity.build())// Execute the request in a new HttpContextvalctx=HttpClientContext.create()valresponse:CloseableHttpResponse=httpClient.execute(httpPost,ctx)// Read the responsevalentity=response.getEntityvalresult=EntityUtils.toString(entity)// Close the responseif(response!=null)response.close()result})}}