Facebook C# SDK – Multiple file uploads in Batch Requests
In v5 of the Facebook C# SDK we introduced batch requests through Batch and BatchAsync methods. Though it supported all the http methods such as GET, POST and DELETE a major feature for uploading files using batch requests was left out (as Facebook hadn’t finalized multiple file uploading).
Starting from v5.0.35 the SDK supports multiple file uploads in batch requests. In this blog post I’m going to explain some internal details on how it works and how can you start attaching multiple files in your single batch request.
dynamic result = fb.Batch(
new FacebookBatchParameter(HttpMethod.Post, "/me/photos", new Dictionary<string, object> { { "message", "picture 1 msg" }, { "pic1", new FacebookMediaObject { ContentType = "image/jpeg", FileName = "Tulips.jpg" }.SetValue(File.ReadAllBytes(@"C:\Users\Public\Pictures\Sample Pictures\Tulips.jpg")) } }),
new FacebookBatchParameter(HttpMethod.Post, "/me/photos", new Dictionary<string, object> { { "message", "picture 2 msg" }, { "pic2", new FacebookMediaObject { ContentType = "image/jpeg", FileName = "Penguins.jpg" }.SetValue(File.ReadAllBytes(@"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg")) } }));
The above example uploads 2 files using the batch request using the “/me/photos” graph path.
The most important part here is the parameters. The parameters must be of type IDictionary<string,object> if you want to attach files. Let us look carefully at how we can attach the FacebookMediaObject.
{ "pic1", new FacebookMediaObject { ContentType = "image/jpeg", FileName = "Tulips.jpg" }.SetValue(File.ReadAllBytes(@"C:\Users\Public\Pictures\Sample Pictures\Tulips.jpg")) }
You could attach the FacebookMediaObject the same way as you would do with normal Post method. To make your life easier, the SDK now returns FacebookMediaObject instead of void for the SetValue thus allowing you to have a sort of fluent api for setting the value of the media objects.
Note the key of the parameters for FacebookMediaObject. The first one is “pic1” and the second one is “pic2”, this can basically be anything you like but make sure to make it unique as it is used as the name in the multipart/form-data when you upload the file.
Looking at fiddler this would be how it looks.
Content-Disposition: form-data; name="pic1"; filename="Tulips.jpg"
Facebook C# SDK being smart automatically adds a parameter called “attached_files”. The attached_files have is set to the key of the parameter. (The attached_files is only added if you have exactly one media object in the root level of the FacebookBatchParameter.)
{"method":"POST","attached_files":"pic1", "body":"message=picture+1+msg", "relative_url":"me/photos"}
Since there has been some major change in some part of codes, we are making it a beta release instead of RTW. So make sure to try it out and report us any bugs before we release the RTW next week.