简体   繁体   English

C# Xamarin 文件上传到 API 使用 RestSharp 工作,但使用 HttpClient 不起作用

[英]C# Xamarin file upload to API works using RestSharp but does not work using HttpClient

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/ )我正在尝试将图像文件从手机摄像头上传到我的 Xamarin 应用程序中的 BuddyPress API(可以在此处找到 API 调用文档 - https://developer.buddypress.org/bp-rest-api/reference/attachments /会员头像/ )

I can do this successfully using RestSharp as follows;我可以使用 RestSharp 成功地做到这一点,如下所示;

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;但是,我在应用程序中的所有其他请求都是使用 HttpClient 执行的,我想保持一致,所以我想出了以下函数来替换它;

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" }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM