用 C# 上传 Facebook 照片?

发布于 2024-10-19 15:31:53 字数 3289 浏览 1 评论 0原文

我正在尝试使用 Facebook Graph API 从 Windows Phone Silverlight 应用程序将照片上传到 Facebook,但收到错误:(#324) 需要上传文件。任何人都可以看到我的代码有什么问题吗?

    internal void PublishPhoto(System.IO.MemoryStream stream, string message, string accessToken)
    {
        var requestUriString = string.Format(
            CultureInfo.InvariantCulture, 
            "https://graph.facebook.com/{0}/photos?access_token={1}&message={2}",
            "me",
            accessToken,
            message);

        var webRequest = WebRequest.CreateHttp(requestUriString);

        webRequest.Method = "POST";

        var boundary = "7db3d9202a1";
        webRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

        webRequest.BeginGetRequestStream(new AsyncCallback(delegate (IAsyncResult result)
            {
                GetRequestStream(stream, boundary, result);

                BeginGetResponse(webRequest);

            }), webRequest);
    }

    private static void GetRequestStream(System.IO.MemoryStream imageStream, string boundary, IAsyncResult result)
    {
        var webRequest2 = result.AsyncState as HttpWebRequest;

        using (var requestStream = webRequest2.EndGetRequestStream(result))
        {
            using (StreamWriter writer = new StreamWriter(requestStream))
            {
                writer.WriteLine("--{0}\r", boundary);
                writer.WriteLine("Content-Disposition: form-data; filename=\"sketch.jpg\"\r");
                writer.WriteLine("Content-Type: image/jpg\r");

                byte[] buffer = imageStream.GetBuffer();
                requestStream.Write(buffer, 0, buffer.Length);

                writer.WriteLine("\r");
                writer.WriteLine("--{0}--\r", boundary);
            }

            imageStream.Close();
        }
    }

    private static void BeginGetResponse(HttpWebRequest webRequest)
    {
        webRequest.BeginGetResponse(new AsyncCallback(delegate(IAsyncResult result2)
        {
            var webRequest2 = result2.AsyncState as HttpWebRequest;

            try
            {
                using (var response = webRequest2.EndGetResponse(result2))
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            System.Diagnostics.Debug.WriteLine(reader.ReadToEnd());
                        }
                    }
                }
            }
            catch (WebException we)
            {
                System.Diagnostics.Debug.WriteLine(we.Message);

                using (var responseStream = we.Response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        var errorJson = reader.ReadToEnd();

                        var response = Newtonsoft.Json.JsonConvert.DeserializeObject<FacebookErrorResponse>(errorJson);

                        System.Diagnostics.Debug.WriteLine("Could not upload image to Facebook: {0}", response.Error.Message);
                    }
                }
            }
        }), webRequest);
    }
}

I am trying to upload an photo to Facebook from a Windows Phone Silverlight application using the Facebook Graph API but I am getting an error: (#324) Requires upload file. Can anyone see anything wrong in my code?

    internal void PublishPhoto(System.IO.MemoryStream stream, string message, string accessToken)
    {
        var requestUriString = string.Format(
            CultureInfo.InvariantCulture, 
            "https://graph.facebook.com/{0}/photos?access_token={1}&message={2}",
            "me",
            accessToken,
            message);

        var webRequest = WebRequest.CreateHttp(requestUriString);

        webRequest.Method = "POST";

        var boundary = "7db3d9202a1";
        webRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

        webRequest.BeginGetRequestStream(new AsyncCallback(delegate (IAsyncResult result)
            {
                GetRequestStream(stream, boundary, result);

                BeginGetResponse(webRequest);

            }), webRequest);
    }

    private static void GetRequestStream(System.IO.MemoryStream imageStream, string boundary, IAsyncResult result)
    {
        var webRequest2 = result.AsyncState as HttpWebRequest;

        using (var requestStream = webRequest2.EndGetRequestStream(result))
        {
            using (StreamWriter writer = new StreamWriter(requestStream))
            {
                writer.WriteLine("--{0}\r", boundary);
                writer.WriteLine("Content-Disposition: form-data; filename=\"sketch.jpg\"\r");
                writer.WriteLine("Content-Type: image/jpg\r");

                byte[] buffer = imageStream.GetBuffer();
                requestStream.Write(buffer, 0, buffer.Length);

                writer.WriteLine("\r");
                writer.WriteLine("--{0}--\r", boundary);
            }

            imageStream.Close();
        }
    }

    private static void BeginGetResponse(HttpWebRequest webRequest)
    {
        webRequest.BeginGetResponse(new AsyncCallback(delegate(IAsyncResult result2)
        {
            var webRequest2 = result2.AsyncState as HttpWebRequest;

            try
            {
                using (var response = webRequest2.EndGetResponse(result2))
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            System.Diagnostics.Debug.WriteLine(reader.ReadToEnd());
                        }
                    }
                }
            }
            catch (WebException we)
            {
                System.Diagnostics.Debug.WriteLine(we.Message);

                using (var responseStream = we.Response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        var errorJson = reader.ReadToEnd();

                        var response = Newtonsoft.Json.JsonConvert.DeserializeObject<FacebookErrorResponse>(errorJson);

                        System.Diagnostics.Debug.WriteLine("Could not upload image to Facebook: {0}", response.Error.Message);
                    }
                }
            }
        }), webRequest);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

魂牵梦绕锁你心扉 2024-10-26 15:31:53

尝试在 Content-Disposition 标头中指定“源”名称以及文件名,即

writer.WriteLine("Content-Disposition: form-data; name=\"source\"; filename=\"sketch.jpg\"\r");

Try specifying a name of "source" as well as a filename in the Content-Disposition header, i.e.

writer.WriteLine("Content-Disposition: form-data; name=\"source\"; filename=\"sketch.jpg\"\r");
风月客 2024-10-26 15:31:53

好吧,我第一次错了,但现在我明白了。

我们上面已经解决的第一个问题是,您在 POST 正文中缺少每个边界之前的“--”以及最后一个边界之后的“--”。

第二个问题是,在写入图像内容之前,您没有在 MIME 标头后面留下空行。

第三个问题是,在将图像数据写入其底层流之前,您没有刷新写入器(除非手机上的 silverlight 与自动刷新 StreamWriter 中的普通 .NET 不同)。

总而言之,这应该有效:

            writer.WriteLine("--{0}\r", boundary);
            writer.WriteLine("Content-Disposition: form-data; filename=\"sketch.jpg\"\r");
            writer.WriteLine("Content-Type: image/jpg\r");
            writer.WriteLine("\r");
            writer.Flush();

            byte[] buffer = imageStream.GetBuffer();
            requestStream.Write(buffer, 0, buffer.Length);

            writer.WriteLine("\r");
            writer.WriteLine("--{0}--\r", boundary);

Ok, I was wrong the first time around, but now I have it.

The first problem, which we already took care of above, was that you were missing the "--" before each boundary and the "--" after the last boundary in the POST body.

The second problem is that you're not leaving a blank line after the MIME headers before writing the image content.

The third problem is that you're not flushing the writer before writing the image data to its underlying stream (unless silverlight on a phone is different from normal .NET in auto-flushing StreamWriters).

To sum up, this should work:

            writer.WriteLine("--{0}\r", boundary);
            writer.WriteLine("Content-Disposition: form-data; filename=\"sketch.jpg\"\r");
            writer.WriteLine("Content-Type: image/jpg\r");
            writer.WriteLine("\r");
            writer.Flush();

            byte[] buffer = imageStream.GetBuffer();
            requestStream.Write(buffer, 0, buffer.Length);

            writer.WriteLine("\r");
            writer.WriteLine("--{0}--\r", boundary);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文