pokopang pokopang - 25 days ago 16
C# Question

C#: Upload Photo To Twitter From Unity

currently I am working with unity. In this project, I need to post some status with image to twitter. However, I got a problem to upload the image to the Twitter.

Here is the code, which I used to upload the Image:

private const string UploadMediaURL = "https://upload.twitter.com/1.1/media/upload.json";
public static IEnumerator UploadMedia(string consumerKey, string consumerSecret, string filePath, AccessTokenResponse response){
Dictionary<string, string> mediaParameters = new Dictionary<string, string>();
mediaParameters.Add("media", System.Convert.ToBase64String(File.ReadAllBytes(filePath)));

// Add data to the form to post.
WWWForm mediaForm = new WWWForm();
mediaForm.AddField("media", System.Convert.ToBase64String(File.ReadAllBytes(filePath)));

print (System.Convert.ToBase64String (File.ReadAllBytes (filePath)));

// HTTP header
var mediaHeaders = new Hashtable();
mediaHeaders["Authorization"] = GetHeaderWithAccessToken("POST", UploadMediaURL, consumerKey, consumerSecret, response, mediaParameters);

WWW mw = new WWW(UploadMediaURL, mediaForm.data, mediaHeaders);
yield return mw;

if (!string.IsNullOrEmpty (mw.error)) {
Debug.Log(string.Format("PostTweet - failed. {0}"));
} else {
SetMediaWeb(mw);
}
}


When I call above method, I got bellow error:


UriFormatException: Uri is longer than the maximum {0} characters.
System.Uri.EscapeDataString (System.String stringToEscape)


FYI image size is not big, it's only 23 kb and the type of the image is png.

What is wrong with my code. Thanks for your help.

Answer

I also had the same issue. I solved it by reducing the size of the image I was trying to post. I'm not sure what the limit is but I found 256*256 jpg worked fine.

I also noticed your code is a little different to mine. Here's my code

Dictionary<string, string> parameters = new Dictionary<string, string>();
string encoded64ImageData = ImageToBase64( imageData );
parameters.Add("media_data", encoded64ImageData );

// Add data to the form to post.
WWWForm form = new WWWForm();
form.AddField( "media_data", encoded64ImageData );

// HTTP header
Dictionary<string, string> headers = new Dictionary<string, string>();
string url = UploadMediaURL;
string auth = GetHeaderWithAccessToken("POST", url, consumerKey, consumerSecret, accessToken, parameters);
headers.Add( "Authorization", auth );
headers.Add( "Content-Transfer-Encoding", "base64" );

WWW web = new WWW(url, form.data, headers);
yield return web;

The Twitter docs say you need to use media_data when submitting 64bit encoded media. media/upload

I also read that you need to define "Content-Transfer-Encoding=base64" when submitting 64bit data forms... This may or may not be necessary, I haven't tried it without.