从 Xamarin 读取多部分数据

Ans*_*shu 6 c# xamarin.ios xamarin.android xamarin xamarin.forms

我们需要将给定目录的 jpeg 文件发送到 Xamarin 应用程序。

以下是 Web API 中的代码。

public HttpResponseMessage DownloadMutipleFiles()
{
    name = "DirectoryName";
    var content = new MultipartContent();
    var ids = new List<int> { 1,2};

    var objectContent = new ObjectContent<List<int>>(ids, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
    content.Add(objectContent);

    var file1Content = new StreamContent(new FileStream(@"D:\Photos\" + name+"\\"+ "BL1408037_20191031124058_0.jpg", FileMode.Open));
    file1Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
    content.Add(file1Content);

    var file2Content = new StreamContent(new FileStream(@"D:\Photos\" + name + "\\" + "BL1408037_20191031124058_1.jpg", FileMode.Open));
    file2Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
    content.Add(file2Content);

    var response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = content;
    return response;
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮助了解如何从 Xamarin 应用程序中阅读吗?提前致谢

Saa*_*mer 0

这是我能够用来将图像作为多部分数据文件发送的功能!我只是获取 Xamarin Essentials 图像选择器提供给我的字节数组并将其传递到此函数中:

    public async Task SubmitImage(byte[] image, string imageName)
    {
      using (var client = new HttpClient())
      {
        string url = $"..."; // URL goes here

        var token = Preferences.Get("AccessToken", "");
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        var stream = new MemoryStream(image);

        var content = new StreamContent(stream);

        //Without a name we can't actually put the file in IFormFile. We need the equivalent
        //"name" value to be "file" (used if you upload via an <input> tag). We could call it
        //anything but file is simple
        content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
          FileName = imageName,
          Name = "file"
        };
        content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

        var multipartContent = new MultipartFormDataContent();
        multipartContent.Add(content);

        var result = await client.PostAsync(url, multipartContent);
      }
    }
Run Code Online (Sandbox Code Playgroud)

您也可以使用控制台应用程序进行测试,只需从计算机发送图片即可,而不是通过应用程序执行此操作