HttpClient发布带有Facebook Graph消息的照片

时间:2014-08-07 10:39:43

标签: c# facebook-graph-api-v2.0

问题

我正在尝试通过消息将照片上传到Facebook API。

代码段 - 上传

        requestUri = "https://graph.facebook.com/v2.0/me/photos?access_token=MyAccessToken"

        var streamContent = new StreamContent(fileStream);
        streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "\"files\"",
            FileName = "\"image.jpg\""
        };
        streamContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); 
        var messageContent = new StringContent("message=HelloWorld");
        var resultJson = webRequestClient.Post(requestUri, new MultipartFormDataContent()
        {
            messageContent,
            streamContent, 
        });

代码 - webRequestClient

    public string Post(string uri, HttpContent postData)
    {
        return PostAsync(uri, postData).Result;
    }

    public async Task<string> PostAsync(string uri, HttpContent httpContent)
    {
        string resultStream;
        using (var httpClient = new HttpClient())
        {
            var response = await httpClient.PostAsync(uri, httpContent);
            response.EnsureSuccessStatusCode();
            resultStream = await response.Content.ReadAsStringAsync();
        }
        return resultStream;
    }

备注

  • 如果我删除“messageContent”:它上传了他的图片
  • 如果我使用MultipartContent:它上传图片但忽略了我的“消息”
  • 现在不要理会为什么我不使用异步功能
  • 当它失败时,我得到“不好”的请求
  • 当我在requestUri中附加“message = helloworld”时,它可以工作,但这不是我的架构中处理这个问题的最灵活的解决方案。

1 个答案:

答案 0 :(得分:0)

检查这会解决您的问题,要么您必须通过流发送图像,那么您不需要明确地告诉该类型是“image / jpeg”。

protected async void TakePictureAndUpload()
{
    var ui = new CameraCaptureUI();
    var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);
    if (file != null)
    {    
        byte[] myPicArray = await GetPhotoBytesAsync(file);
        HttpClient httpClient = new HttpClient();
        httpClient.BaseAddress = new Uri("http://yourdomainname.com");

        MultipartFormDataContent form = new MultipartFormDataContent();
        HttpContent content = new ByteArrayContent(myPicArray);
        form.Add(content, "media", "filename.jpg");
        content = new StringContent("my-username");
        form.Add(content, "username");
        HttpResponseMessage response = await httpClient.PostAsync("directory/my-site.php", form);
     }
}
public async Task<byte[]> GetPhotoBytesAsync(StorageFile file)
{
    IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read);
    var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
    await reader.LoadAsync((uint)fileStream.Size);

    byte[] pixels = new byte[fileStream.Size];
    reader.ReadBytes(pixels);
    return pixels;
}