I'm attempting to upload an image file from the phone camera to a BuddyPress API from my Xamarin app (the API call documentation can be found here - https://developer.buddypress.org/bp-rest-api/reference/attachments/member-avatar/)
I can do this successfully using RestSharp as follows;
public string PostMediaFile(MediaFile data, string path, bool https = false, string authorisationToken = "")
{
var requestMethod = "http://";
if (https)
{
requestMethod = "https://";
}
var serverString = requestMethod + path;
var client = new RestClient(serverString)
{
Timeout = Convert.ToInt32(timeOut)
};
client.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + authorisationToken);
request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
request.AddFile("file", data.Path);
request.AddParameter("action", "bp_avatar_upload");
IRestResponse response = client.Execute(request);
return response.Content;
}
However, all my other requests in the application are performed using HttpClient and I'd like to keep it consistent, so I came up with the follow function to replace this;
public async Task<string> PostMediaFile(MediaFile data, string path, bool https = false, string authorisationToken = "")
{
var memoryStream = new MemoryStream();
data.GetStream().CopyTo(memoryStream);
byte[] fileAsBytes = memoryStream.ToArray();
var fileContent = new ByteArrayContent(fileAsBytes);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
Name = "file",
FileName = Path.GetFileName(data.Path),
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
var content = new MultipartFormDataContent
{
{ fileContent, "file", Path.GetFileName(data.Path) },
{ new StringContent("action"), "bp_avatar_upload" }
};
var requestMethod = "http://";
if (https)
{
requestMethod = "https://";
}
var clientHandler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
};
httpClient = new HttpClient(clientHandler);
if (!string.IsNullOrWhiteSpace(authorisationToken))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorisationToken);
httpClient.DefaultRequestHeaders.UserAgent.TryParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
}
httpClient.Timeout = TimeSpan.FromMilliseconds(timeOut);
var serverString = requestMethod + path;
HttpResponseMessage response = await httpClient.PostAsync(serverString, content);
HttpContent Content = response.Content;
var json = await Content.ReadAsStringAsync();
response.Dispose();
return json;
}
The problem is, obviously it doesn't work, and I don't know why. I just get the following response;
{"code":"bp_rest_attachments_user_avatar_upload_error","message":"Upload failed! Error was: Invalid form submission..","data":{"status":500,"reason":"upload_error"}}
I feel like I'm really close, but not sure where my mistake is.
Ah! it was so simple! I had part of the form data the wrong way around;
{ new StringContent("action"), "bp_avatar_upload" }
should be
{ new StringContent("bp_avatar_upload"), "action" }