2010-12-20 176 views
1

寻找一些代码使用VB.NET中的图形API将照片上传到Facebook。我有Facebook C#SDK,但它不支持上传照片,据我所知。VB.NET使用图形API将照片上传到Facebook

访问照片效果很好,我也可以发送其他内容到Facebook。只是没有照片。

facebook文档讨论将文件附加为表单多部分请求,但我不知道该怎么做。说它没有很好的文件记载就是轻描淡写。即使是我雇用的人来做这种事情也无法让它起作用。

我找到了这个:Upload Photo To Album with Facebook's Graph API,但它只描述了如何在PHP中完成它。

我也看到了不同的网站有关将照片的URL作为HTTP请求的一部分传递的方法,但是在尝试使用本地或远程URL几次后,我总是收到一个错误的URL错误或类似的错误。

有什么想法?

回答

0

您需要将POST请求中的Image传递给Graph API(需要publish_stream权限)。 Facebook文档中提到的是正确的。以下是可能执行此工作的示例代码。在一个方法中使用它。 (代码用C#)

图例 <content>:您需要提供信息。

更新 请发表评论,以改善代码。

string ImageData; 
string queryString = string.Concat("access_token=", /*<Place your access token here>*/); 
string boundary = DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture); 

StringBuilder sb = String.Empty; 
sb.Append("----------").Append(boundary).Append("\r\n"); 
sb.Append("Content-Disposition: form-data; filename=\"").Append(/*<Enter you image's flename>*/).Append("\"").Append("\r\n"); 
sb.Append("Content-Type: ").Append(String.Format("Image/{0}"/*<Enter your file type like jpg, bmp, gif, etc>*/)).Append("\r\n").Append("\r\n"); 

using (FileInfo file = new FileInfo("/*<Enter the full physical path of the Image file>*/")) 
{ 
    ImageData = file.OpenText().ReadToEnd(); 
} 
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString()); 
byte[] fileData = Encoding.UTF8.GetBytes(ImageData); 
byte[] boundaryBytes = Encoding.UTF8.GetBytes(String.Concat("\r\n", "----------", boundary, "----------", "\r\n")); 
var postdata = new byte[postHeaderBytes.Length + fileData.Length + boundaryBytes.Length]; 
Buffer.BlockCopy(postHeaderBytes, 0, postData, 0, postHeaderBytes.Length); 
Buffer.BlockCopy(fileData, 0, postData, postHeaderBytes.Length, fileData.Length); 
Buffer.BlockCopy(boundaryBytes, 0, postData, postHeaderBytes.Length + fileData.Length, boundaryBytes.Length); 

var requestUri = new UriBuilder("https://graph.facebook.com/me/photos"); 
requestUri.Query = queryString; 
var request = (HttpWebRequest)HttpWebRequest.Create(requestUri.Uri); 
request.Method = "POST"; 
request.ContentType = String.Concat("multipart/form-data; boundary=", boundary); 
request.ContentLength = postData.Length; 

using (var dataStream = request.GetRequestStream()) 
{ 
     dataStream.Write(postData, 0, postData.Length); 
} 

request.GetResponse(); 
+0

我终于尝试了这一点,但我得到了相同的“远程服务器返回错误:(400)错误的请求。”我已经用其他方法得到了。我注意到你声明了两次请求变量,vb.net不喜欢这样。 – user548084 2011-01-07 04:47:32

+0

哦耶对不起,我刚刚编辑..和你的问题...你确定你正在使用有效的访问令牌(与发布流扩展权限)..因为该错误通常返回时,你没有一个有效的访问令牌。尝试在浏览器(GET)请求中使用那个具有访问令牌的URI,你仍然会收到错误... – 2011-01-07 06:43:58