Uploading media to Twitter

Hello,

I'm trying to understand Twitter API to upload media, but I'm not able to sort it:

https://dev.twitter.com/rest/public/uploading-media

I don't know even how to start.  I'm experienced in .NET and Javascript


I tried testing this fiddle but it always post the auth icon instead a Base64 image

http://jsfiddle.net/6Jx84/12/
Miguel QuintanaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

kblauCommented:
I am giving credit to where credit is due in this post--to code project and other web sites that helped in creating this post

1.  go to https://apps.twitter.com/
2.  sign on if neccessary
3.  click create new app
4.  Name={nique name}, Description={add description}, Website=http://www.ciphergig.com (use your own website if you can),  Callback URL leave blank, Yes, I agree, click Create your Twitter Application.
5.  Go to the Keys and Access Tokens folder, click Create my access token
6.  Must cut and paste 4 pieces of information Consumer Key, Consumer Secret, Access Token,  Access Token Secret
7.  The following code uploads media to the twitter server, but we need a subsequent (tweet is called update status) tweet iwth a mediaID included.--change the file location to fit your file system location of image file
private void Upload()
        {
            string oauth_consumer_key = "{your consumer key}";
            string oauth_consumer_secret = "{your consumer secret}";
            string oauth_signature_method = "HMAC-SHA1";
            string oauth_version = "1.0";
            string oauth_token = "{your token}";
            string oauth_token_secret = "{your token secret}";
            string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            string oauth_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();

            var URL = "https://upload.twitter.com/1.1/media/upload.json";

            var baseFormat2 = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                                "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";
            var baseString2 = string.Format(baseFormat2,
                oauth_consumer_key,
                oauth_nonce,
                oauth_signature_method,
                oauth_timestamp,
                oauth_token,
                oauth_version);

            baseString2 = string.Concat("POST&", Uri.EscapeDataString(URL),
                         "&", Uri.EscapeDataString(baseString2));

            var compositeKey2 = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                    "&", Uri.EscapeDataString(oauth_token_secret));

            string oauth_signature2;
            using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey2)))
            {
                oauth_signature2 = Convert.ToBase64String(
                    hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString2)));
            }

            var headerFormat2 = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
                               "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
                               "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
                               "oauth_version=\"{6}\"";

            var OAuthSignature = string.Format(headerFormat2,
                                    Uri.EscapeDataString(oauth_nonce),
                                    Uri.EscapeDataString(oauth_signature_method),
                                    Uri.EscapeDataString(oauth_timestamp),
                                    Uri.EscapeDataString(oauth_consumer_key),
                                    Uri.EscapeDataString(oauth_token),
                                    Uri.EscapeDataString(oauth_signature2),
                                    Uri.EscapeDataString(oauth_version)
                            );
            byte[] imageData = ReadImageFile(@"C:\temp\Desert.jpg");
            Encoding EncodingAlgorithm = Encoding.GetEncoding("iso-8859-1");
            string Boundary = DateTime.Now.Ticks.ToString("x");
            string StartBoundary = string.Format("--{0}\r\n", Boundary);
            string EndBoundary = string.Format("\r\n--{0}--\r\n", Boundary);
            string sContentType = "multipart/form-data;boundary=" + Boundary;
            string contentDisposition = "Content-Disposition: form-data; ";
            string contenName = "name=\"media\";\r\n ";
            string contentType = "\r\nContent-Type: application/octet-stream\r\n\r\n";
            string Data = EncodingAlgorithm.GetString(imageData, 0, imageData.Length);
            var contents = new System.Text.StringBuilder();
            contents.Append(String.Format("{0}{1}{2}{3}{4}", StartBoundary, contentDisposition, contenName, contentType, Data));
            contents.Append(EndBoundary);
            byte[] Content = EncodingAlgorithm.GetBytes(contents.ToString());

            var request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "POST";
            request.AllowWriteStreamBuffering = true;
            request.Headers.Add("Authorization", OAuthSignature);
            request.ContentType = sContentType;
            request.ContentLength = Content.Length;

//if you are behind a company firewall
           /* WebProxy intranetPassThrough = new WebProxy();
            intranetPassThrough.BypassProxyOnLocal = true;
            intranetPassThrough.UseDefaultCredentials = true;
            intranetPassThrough.Address = new Uri("http://myproxy:8989");
            request.Proxy = intranetPassThrough; */

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(Content, 0, Content.Length);
            dataStream.Close();
            try
            {
                string MediaID = string.Empty;
                using (var Response = (HttpWebResponse)request.GetResponse())
                {
                    if (Response.StatusCode == HttpStatusCode.OK)
                    {
                        Stream receiveStream = Response.GetResponseStream();
                        StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                        string jsonResult = readStream.ReadToEnd();
                        JObject jobj = JObject.Parse(jsonResult);
                        MediaID = Convert.ToString(jobj["media_id_string"]);
                    }
                }
            }
            catch (WebException ex)
            {
                using (WebResponse response = ex.Response)
                {
                    var httpResponse = (HttpWebResponse)response;

                    try
                    {

                        using (Stream data = response.GetResponseStream())
                        {
                            StreamReader sr = new StreamReader(data);

                            // Twitter didn't like request
                        }
                    }
                    catch (Exception ex2)
                    {
                        // Whole app blew up
                    }
                }
            }
        }

public static byte[] ReadImageFile(string imageLocation)
        {
            byte[] imageData = null;
            FileInfo fileInfo = new FileInfo(imageLocation);
            long imageFileLength = fileInfo.Length;
            FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            imageData = br.ReadBytes((int)imageFileLength);
            return imageData;
        }

8.  If you look at code project site  http://stackoverflow.com/questions/27529403/twitter-api-tweets-with-images-error-code-324-the-validation-of-media-ids-fai

POST https://api.twitter.com/1.1/statuses/update.json HTTP/1.1
Authorization: OAuth oauth_consumer_key="xxxxxxxxxx",oauth_nonce="xxxxx",oauth_signature="xxxxxxxxxxxx",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1418763469",oauth_token="xxxxxxxxxxx",oauth_version="1.0a"
Content-Type: application/x-www-form-urlencoded
Host: api.twitter.com
Content-Length: 117

status=test%20test%20test&media_ids=544959385899122689

--So it is suggested that if you create correct headers and content and include the media_id that the image will be posted.
I could not get this to work, but I did manage to use a library to get a post to work,  and this library has source code on the internet, so if you do some research, you can probably put everything together.

you will need Install-Package twitterizer -Version 2.4.2

Here is how you do a google post (update status):
using System;
 
using System.Collections.Generic;
 
using System.Linq;
 
using System.Text;
 
using System.Web;
 
using System.Web.UI;
 
using System.Web.UI.WebControls;
 
using Twitterizer;

namespace WebApplication35
 
{
 
public partial class WebForm1 : System.Web.UI.Page
 
{
 
protected void Page_Load(object sender, EventArgs e)
 
{
 
var oauth_consumer_key = "{put in }";
 
var oauth_consumer_secret = "{put in }";
 
string oauth_signature_method = "HMAC-SHA1";
 
string oauth_version = "1.0";
 
string oauth_token = "{put in }";
 
string oauth_token_secret = "{put in }";
 
string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
 
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
 
string oauth_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();

try
 
{
 


//These Token values is from Twitter Website after Registration
 
OAuthTokens tokens = new OAuthTokens();
 
tokens.ConsumerKey = oauth_consumer_key;
 
tokens.ConsumerSecret = oauth_consumer_secret;
 
tokens.AccessToken = oauth_token;
 
tokens.AccessTokenSecret = oauth_token_secret;
 
StatusUpdateOptions suo = new StatusUpdateOptions();
 
suo.UseSSL = true;
 
suo.APIBaseAddress = "https://api.twitter.com/1.1/";
 
TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, "hellooo", suo);
 
if (tweetResponse.Result == RequestResult.Success)
 
{
 
//txtTwitGet.Text = " Update Successful.";
 
}
 
else
 
{
 
//txtTwitGet.Text = " Update did not go through.";
 
}
 
}
 
catch (Exception ex)
 
{
 
Response.Write(ex.Message);
 
}

You might get a json error that needs to be corrected, but the post will show up in your twitter and all you need to do now is dig into the twitterizer api and figure out how to put media ids with post.  Please let me know how it is coming, so I can help more, and see what you did (please post) to get this all working.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Twitter

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.