问题
我正在尝试通过消息将照片上传到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;
}
备注
答案 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;
}