Skip to main content
 首页 » 编程设计

C#:从 Unity 上传照片到 Twitter

2024年02月06日11kevingrace

目前我正在使用 unity。在这个项目中,我需要将一些带有图像的状态发布到推特上。但是,我在将图片上传到 Twitter 时遇到了问题。

这是我用来上传图片的代码:

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); 
                } 
            } 

当我调用上述方法时,出现以下错误:

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

仅供引用,图片大小不大,只有 23 kb,图片类型为 png。

我的代码有什么问题。感谢您的帮助。

请您参考如下方法:

我也遇到了同样的问题。我通过减小我尝试发布的图像的大小来解决它。我不确定限制是多少,但我发现 256*256 jpg 效果很好。

我还注意到您的代码与我的略有不同。这是我的代码

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; 

Twitter 文档说您在提交 64 位编码媒体时需要使用 media_data。 media/upload

我还读到在提交 64 位数据表单时需要定义“Content-Transfer-Encoding=base64”...这可能是必要的,也可能不是必要的,我没有尝试过。