gpt4 book ai didi

c# - 从 Xamarin 读取多部分数据

转载 作者:行者123 更新时间:2023-12-04 12:02:43 26 4
gpt4 key购买 nike

我们需要将给定目录的 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 应用程序中阅读吗?提前致谢

最佳答案

这是我能够用来将图像作为多部分数据文件发送的功能!我只是将 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);
}
}
您也可以使用控制台应用程序进行测试,只需从您的计算机发送图片,而不是通过应用程序执行此操作

关于c# - 从 Xamarin 读取多部分数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62028970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com