0

我正在尝试使用 ASP.NET 和 C# 将照片上传到 Facebook。使用 Facebook oAuth 登录效果很好,并且访问令牌是正确的,但我就是不知道如何使用它来发布照片。感谢任何帮助,真的很难理解 Facebooks API 和 ASP.NET 如何协同工作。

4

1 回答 1

0

您可以使用现成的组件

http://computerbeacon.net/library/960n60e000000

或者使用以下代码(从源代码中获得)

/// <summary>
/// Publishes a photo to a specific album and post it on the user's wall
/// </summary>
/// <param name="photo">photo to be published</param>
/// <param name="message">message with this photo</param>
/// <returns>PhotoID of the photo published</returns>
public string PublishPhoto(System.Drawing.Bitmap photo, string message, string AccessToken)
{
    string AlbumID = "me";//post to wall , no spesific album
    System.IO.MemoryStream MS = new System.IO.MemoryStream();
    photo.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);
    byte[] Imagebytes = MS.ToArray();
    MS.Dispose();

    //Set up basic variables for constructing the multipart/form-data data
    string newline = "\r\n";
    string boundary = DateTime.Now.Ticks.ToString("x");
    string data = "";

    //Construct data
    data += "--" + boundary + newline;
    data += "Content-Disposition: form-data; name=\"message\"" + newline + newline;
    data += message + newline;

    data += "--" + boundary + newline;
    data += "Content-Disposition: form-data; filename=\"test.jpg\"" + newline;
    data += "Content-Type: image/jpeg" + newline + newline;

    string ending = newline + "--" + boundary + "--" + newline;

    //Convert data to byte[] array
    System.IO.MemoryStream finaldatastream = new System.IO.MemoryStream();
    byte[] databytes = System.Text.Encoding.UTF8.GetBytes(data);
    byte[] endingbytes = System.Text.Encoding.UTF8.GetBytes(ending);
    finaldatastream.Write(databytes, 0, databytes.Length);
    finaldatastream.Write(Imagebytes, 0, Imagebytes.Length);
    finaldatastream.Write(endingbytes, 0, endingbytes.Length);
    byte[] finaldatabytes = finaldatastream.ToArray();
    finaldatastream.Dispose();

    //Make the request
    System.Net.WebRequest request = System.Net.HttpWebRequest.Create(string.Format("https://graph.facebook.com/{0}/photos?access_token={1}", AlbumID, AccessToken));
    request.ContentType = "multipart/form-data; boundary=" + boundary;
    request.ContentLength = finaldatabytes.Length;
    request.Method = "POST";
    using (System.IO.Stream RStream = request.GetRequestStream())
    {
        RStream.Write(finaldatabytes, 0, finaldatabytes.Length);
    }
    System.Net.WebResponse WR = request.GetResponse();
    string _Response = "";
    using (System.IO.StreamReader sr = new System.IO.StreamReader(WR.GetResponseStream()))
    {
        _Response = sr.ReadToEnd();
    }
    string Id = "";//get the Id from the Response
    return Id;
}
于 2012-04-29T10:23:57.633 回答