2010-12-20 71 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

相關問題