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”时,它可以工作,但这不是我的架构中处理此问题的最灵活的解决方案。
4

1 回答 1

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;
}
于 2014-08-24T21:37:31.400 回答