【问题标题】:Reading Multipart Data from Xamarin从 Xamarin 读取多部分数据
【发布时间】:2020-09-13 15:49:15
【问题描述】:

我们需要将给定目录的 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;
}

有人可以帮助解决如何从 Xamarin 应用程序中读取数据吗?提前致谢

【问题讨论】:

  • 根据您的描述,您已经使用web api下载字典中的jpeg,现在您想将这些数据传递给Xamarin应用程序吗?
  • 是的,我们确实从 API 中提到的代码中接收到 Xamarin 代码中的数据,但我们无法从中生成两个图像。任何帮助是极大的赞赏。谢谢。
  • 如果你做了一个。向您的端点发出请求,您得到正确的响应了吗?
  • 这也是问题之一。当我从 Postman 或浏览器访问端点时,我得到了一大块数据。在大小上,它等于两个图像的总和。但我仍然可以想办法从发送的数据块中生成两个图像。
  • 您是否明确需要将数据作为多部分数据传递?

标签: c# xamarin xamarin.forms xamarin.android xamarin.ios


【解决方案1】:

这是我可以用来将图像作为多部分数据文件发送的功能!我只是把 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);
      }
    }

您也可以使用控制台应用程序对此进行测试,然后从您的计算机发送一张图片,而不是通过应用程序进行此操作

【讨论】:

    猜你喜欢
    • 2019-10-13
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 2023-02-07
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多