Search code examples
c#.nettwitterhammock

Upload Image to Twitter


I am trying to upload an image to Twitter using Twitter API Version 1.1 and the update_with_media.json method.

https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media

This is the code I have so far, yet despite numerous variations I can not get a successful upload.

    public TwitterResponse UpdateStatus(string message, String fileName, String contentType, byte[] image)
    {
        RestClient client = new RestClient
        {
            Authority = TwitterConstants.Authority,
            VersionPath = TwitterConstants.Version

        };

        message = HttpUtility.HtmlEncode(message);

        client.AddHeader("content-type", "multipart/form-data");

        client.AddField("status", message);
        client.AddField("media[]", Convert.ToBase64String(image) + ";filename=" + fileName + ";type=" + contentType);

        RestRequest request = new RestRequest
        {
            Credentials = this.Credentials,
            Path = "statuses/update_with_media.json",
            Method = Hammock.Web.WebMethod.Post

        };

        return new TwitterResponse(client.Request(request));
    }

I am using Hammock to perform these requests.

Just to rule out possible other issues, I can successfully post a status update to Twitter using the update.json method.

I have also tried using the client.AddFile method and using Fiddler it looks like everything is in place. But the error message I keep getting back is

{"errors":[{"code":195,"message":"Missing or invalid url parameter"}]}

Solution

  • Instead of using native Twitter API, you can use TweeterSharp plugin available at Nuget.

    Sample with description is written at this article by me Post message with image on twitter using C#

    In particular this is the code snippet

    using (var stream = new FileStream(imagePath, FileMode.Open))
                {
                    var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions
                    {
                        Status = message,
                        Images = new Dictionary<string, Stream> { { "john", stream } }
                    });
                    lblResult.Text = result.Text.ToString();
                }
    

    The complete demo is downloadable attached with the article, feel free to download.

    Thanks